diff --git a/addOperators.java b/addOperators.java new file mode 100644 index 00000000..98e1dc39 --- /dev/null +++ b/addOperators.java @@ -0,0 +1,51 @@ +// Time Complexity : O(4^n) +// Space Complexity : O(n) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : None + +class Solution { + List result; + public List addOperators(String num, int target) { + this.result = new ArrayList<>(); + + helper(num, target, 0, 0, 0, 0, new StringBuilder()); + + return result; + } + + private void helper(String num, int target, int i, long curr, long calc, long tail, StringBuilder path) { + + if(i == num.length()) { + if(calc == target && curr == 0) { + result.add(path.toString()); + } + return; + } + + curr = curr * 10 + num.charAt(i) - '0'; + + if(curr > 0) { + helper(num, target, i + 1, curr, calc, tail, path); + } + + int le = path.length(); + + if(path.length() == 0) { + path.append(curr); + helper(num, target, i + 1, 0, curr, curr, path); + path.setLength(le); + } else { + path.append("+").append(curr); + helper(num, target, i + 1, 0, calc + curr, curr, path); + path.setLength(le); + + path.append("-").append(curr); + helper(num, target, i + 1, 0, calc - curr, -curr, path); + path.setLength(le); + + path.append("*").append(curr); + helper(num, target, i + 1, 0, calc - tail + (tail * curr), tail * curr, path); + path.setLength(le); + } + } +} diff --git a/combinationSum.java b/combinationSum.java new file mode 100644 index 00000000..ef1eb158 --- /dev/null +++ b/combinationSum.java @@ -0,0 +1,32 @@ +// Time Complexity : O(n * 2^(m+n) +// Space Complexity : O(n * h) -> O(n^2) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : None +class Solution { + List> result; + public List> combinationSum(int[] candidates, int target) { + this.result = new ArrayList<>(); + helper(candidates, target, 0, new ArrayList<>()); + return result; + } + + private void helper(int[] candidates, int target, int pivot, List path) { + + //base case + if (target < 0) return; + + if (target == 0) { + result.add(path); + return; + } + + for (int i = pivot; i < candidates.length; i++) { + //action + List list = new ArrayList<>(path); + list.add(candidates[i]); + + //recurse + helper(candidates, target - candidates[i], i, list); + } + } +}