diff --git a/282. Expression Add Operators/Solution.java b/282. Expression Add Operators/Solution.java new file mode 100644 index 00000000..24a61a88 --- /dev/null +++ b/282. Expression Add Operators/Solution.java @@ -0,0 +1,64 @@ +class Solution { + public List addOperators(String num, int target) { + + List result = new ArrayList(); + + helper(num, target, 0, 0, 0, new StringBuilder(), result); + + return result; + + } + + public void helper(String num, int target, long calc, long tail, int pivot, StringBuilder path, + List result) { + + //base case + if (pivot == num.length()) { + if (calc == target) { + result.add(path.toString()); + } + } + + //for loop + for (int i = pivot; i < num.length(); i++) { + + if (num.charAt(pivot) == '0' && i != pivot) { + break; + } + + long cur = Long.parseLong(num.substring(pivot, i + 1)); // substring take +1 address to strip + + int length = path.length(); + + if (pivot == 0) { + + path.append(cur); + + helper(num, target, cur, cur, i + 1, path, result); + + path.setLength(length); + + } else { + + //+ + path.append("+").append(cur); + helper(num, target, calc + cur, cur, i + 1, path, result); + path.setLength(length); + + //- + path.append("-").append(cur); + helper(num, target, calc - cur, -cur, i + 1, path, result); + path.setLength(length); + + //* + path.append("*").append(cur); + helper(num, target, calc - tail + tail * cur, tail * cur, i + 1, path, result); + path.setLength(length); + + } + } + } +} + +// TC - 4*n +// SC - O(n) \ No newline at end of file diff --git a/39. Combination Sum/Solution.java b/39. Combination Sum/Solution.java new file mode 100644 index 00000000..09fdc287 --- /dev/null +++ b/39. Combination Sum/Solution.java @@ -0,0 +1,40 @@ +class Solution { + public List> combinationSum(int[] candidates, int target) { + + List> result = new ArrayList<>(); + + helper(target, candidates, result, 0, new ArrayList<>()); + + return result; + + } + + public void helper(int target, int[] candidates, List> result, int pivot, List path){ + + //base case + if(target == 0){ + result.add(new ArrayList<>(path)); + return; + } + + if(target < 0 || pivot == candidates.length){ + return; + } + + + //for loop base recursion + for(int i = pivot; i < candidates.length; i++){ + + path.add(candidates[i]); + + helper(target - candidates[i], candidates, result, i, path); + + //backtrack + path.remove(path.size() - 1); + + } + } +} + +// TC - O(2^(m+n)) +// SC - O(n^2) \ No newline at end of file