diff --git a/CombinationSumBackTrack.java b/CombinationSumBackTrack.java new file mode 100644 index 00000000..9a9e7809 --- /dev/null +++ b/CombinationSumBackTrack.java @@ -0,0 +1,38 @@ +//Time Complexity: 2 power (m+n) +//Space Compexity: O(m+n) + O(n) +//For primitive data type in result instead of exact path (list of integers etc.) we can use DP else use Backtracking for optimal solution + +//Back Tracking +class Solution { + List> result; + public List> combinationSum(int[] candidates, int target) { + this.result = new ArrayList<>(); + if(candidates == null || candidates.length == 0) return result; + helper(candidates, 0, target, new ArrayList<>()); + return result; + } + + private void helper(int[] candidates, int i, int target, List path) + { + //Base case + if(target < 0 || i == candidates.length){ + return; + } + + if(target == 0) + { + result.add(new ArrayList<>(path)); + return; + } + + //case 0 + helper(candidates, i+1, target, path); + + //case 1 + path.add(candidates[i]); + helper(candidates, i, target-candidates[i], path); + + //backtrack + path.remove(path.size() - 1); // remove last element added + } +} \ No newline at end of file diff --git a/ExpressionAddOperators.java b/ExpressionAddOperators.java new file mode 100644 index 00000000..07924e1b --- /dev/null +++ b/ExpressionAddOperators.java @@ -0,0 +1,46 @@ +//Time Complexity : O(4 power n) +//Space Complexity: O(h) +class Solution { + List result; + public List addOperators(String num, int target) { + result = new ArrayList<>(); + if(num == null || num.length() == 0) return result; + helper(num, target, "", 0, 0, 0); + return result; + } + + private void helper(String num, int target, String path, long calc, long tail, int index) + { + //base case + if(index == num.length()){ + if(target == calc){ + result.add(path); + return; + } + } + //logic + + for(int i = index; i < num.length(); i++) + { + if(num.charAt(index) =='0' && index != i) + { + continue; + } + long curr = Long.parseLong(num.substring(index, i+1)); + if(index == 0){ + helper(num, target, path + curr, curr, curr, i+1); + } + else + { + // + case + helper(num, target, path + "+" + curr, calc + curr, curr, i+1); + + // - case + helper(num, target, path + "-" + curr, calc - curr, -curr, i+1); + + // * case + helper(num, target, path + "*" + curr, calc - tail + tail * curr, tail * curr, i+1); + } + } + } +} \ No newline at end of file