From 66857cbfc2743e535996fcc8f22c2b3f8947fba0 Mon Sep 17 00:00:00 2001 From: dhruvil15 <76967484+dhruvil15@users.noreply.github.com> Date: Thu, 21 May 2026 20:29:32 -0400 Subject: [PATCH] Complete BackTracking-1 --- Problem70.java | 31 ++++++++++++++++++++++++++++ Problem71.java | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 Problem70.java create mode 100644 Problem71.java diff --git a/Problem70.java b/Problem70.java new file mode 100644 index 00000000..b27d518e --- /dev/null +++ b/Problem70.java @@ -0,0 +1,31 @@ +// Time Complexity : O(2 ^ (m+n)) where m is the candidates length and n is the target +// Space Complexity : O(n) + +class Solution { + public List> combinationSum(int[] candidates, int target) { + List> result = new ArrayList<>(); + helper(candidates, target, 0, new ArrayList<>(), result); + return result; + } + + private void helper(int[] candidates, int target, int pivot, List path, List> result) { + //base + if (target < 0 || candidates.length == pivot) { + return; + } + + if (target == 0) { + result.add(new ArrayList<>(path)); + return; + } + + for (int i = pivot; i < candidates.length; i++) { + //action + path.add(candidates[i]); + //recurse + helper(candidates, target - candidates[i], i, path, result); + //backtrack + path.remove(path.size() - 1); + } + } +} \ No newline at end of file diff --git a/Problem71.java b/Problem71.java new file mode 100644 index 00000000..8b5dccea --- /dev/null +++ b/Problem71.java @@ -0,0 +1,55 @@ +// Time Complexity : O(4^n) +// Space Complexity : O(n) + +class Solution { + List result; + public List addOperators(String num, int target) { + + this.result = new ArrayList<>(); + + helper(num, target, 0, 0, 0, new StringBuilder()); + + return result; + } + + private void helper(String num, int target, int pivot, long calc, long tail, StringBuilder path){ + + if(pivot == num.length()){ + if(calc == target){ + result.add(path.toString()); + } + } + + for(int i = pivot; i < num.length(); i++){ + + if(num.charAt(pivot) == '0' && i != pivot) break; + + long curr = Long.parseLong(num.substring(pivot, i+1)); + + int le = path.length(); + + if(pivot == 0){ + path.append(curr); + helper(num, target, i+1, curr, curr, path); + path.setLength(le); + + }else{ + + // + + path.append("+").append(curr); + helper(num, target, i+1, calc + curr, curr, path); + path.setLength(le); + + // - + path.append("-").append(curr); + helper(num, target, i+1, calc - curr, -curr, path); + path.setLength(le); + + // * + path.append("*").append(curr); + helper(num, target, i+1, calc - tail + (tail * curr), tail * curr, path); + path.setLength(le); + } + } + } +} \ No newline at end of file