diff --git a/Problem1.java b/Problem1.java new file mode 100644 index 00000000..ce9f8f60 --- /dev/null +++ b/Problem1.java @@ -0,0 +1,25 @@ +class Solution { + List> result; + public List> combinationSum(int[] candidates, int target) { + if (candidates == null || candidates.length == 0) return new ArrayList<>(); + + result = new ArrayList<>(); + + backtrack(candidates, target, 0, 0, new ArrayList<>()); + + return result; + } + + public void backtrack(int[] candidates, int target, int index, int currSum, List combination) { + if (currSum == target) { + result.add(new ArrayList<>(combination)); + return; + } + if (currSum > target || index == candidates.length) return; + + combination.add(candidates[index]); + backtrack(candidates, target, index, currSum + candidates[index], combination); + combination.removeLast(); + backtrack(candidates, target, index + 1, currSum, combination); + } +} diff --git a/Problem2.java b/Problem2.java new file mode 100644 index 00000000..4620c1fc --- /dev/null +++ b/Problem2.java @@ -0,0 +1,42 @@ +class Solution { + List result; + public List addOperators(String num, int target) { + if (num == null || num.length() == 0) return new ArrayList<>(); + + result = new ArrayList<>(); + + backtrack(num, target, 0, 0, 0, ""); + + return result; + } + + public void backtrack(String num, int target, int index, long calc, long tail, String exp) { + + if (index == num.length()) { + if (target == calc) result.add(exp); + return; + } + + for (int i=index; i