diff --git a/Problem1.java b/Problem1.java new file mode 100644 index 00000000..c2d7c512 --- /dev/null +++ b/Problem1.java @@ -0,0 +1,38 @@ + +// Time complexity is O( 2 ^ (T/M)) where is target is the target and m is the smallest number inthe candidatest the extra length we get when we keep on choosing smallest number +//Space complexity is O(T/M) +// combination sum using backtracking + +class Solution { + List> result; + public List> combinationSum(int[] candidates, int target) { + this.result = new ArrayList<>(); + helper(candidates, 0, target, new ArrayList<>() ); + + return result; + + } + + private void helper(int[] candidates, int i, int target, List path){ + + if(target < 0 || i == candidates.length) { + return ; + } + + if(target == 0){ + result.add(new ArrayList<>(path)); + return; + } + //choose + path.add(candidates[i]); + helper(candidates, i, target- candidates[i], path); + path.remove(path.size()-1); + //not choose + + helper(candidates, i+1, target, path); + + + + + } +} diff --git a/Problem2.java b/Problem2.java new file mode 100644 index 00000000..2c06ad80 --- /dev/null +++ b/Problem2.java @@ -0,0 +1,81 @@ +//space complexity o(n) +//time complexity o(4^n) +//using dfs for loop exploring every solution +class Solution { + + List result = new ArrayList<>(); + + public List addOperators(String num, int target) { + + helper(num, 0, "", target, 0, 0); + + return result; + } + + private void helper(String num, + int i, + String path, + int target, + long totalSum, + long prev) { + + if (i == num.length()) { + + if (totalSum == target) { + result.add(path); + } + + return; + } + + long current = 0; + + for (int j = i; j < num.length(); j++) { + + if (j > i && num.charAt(i) == '0') { + break; + } + + current = current * 10 + (num.charAt(j) - '0'); + + String currentString = num.substring(i, j + 1); + + if (i == 0) { + + helper( + num, + j + 1, + currentString, + target, + current, + current); + + } else { + + helper( + num, + j + 1, + path + "+" + currentString, + target, + totalSum + current, + current); + + helper( + num, + j + 1, + path + "-" + currentString, + target, + totalSum - current, + -current); + + helper( + num, + j + 1, + path + "*" + currentString, + target, + totalSum - prev + prev * current, + prev * current); + } + } + } +}