From 857da0557d807146e6f3ce0123a8a02761d1aae3 Mon Sep 17 00:00:00 2001 From: Hriday-A Date: Sun, 17 May 2026 19:36:07 -0500 Subject: [PATCH] Backtracking Assignment completed --- combination_sum.java | 57 ++++++++++++++++++++++++++++++++++++ expression_and_operator.java | 40 +++++++++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 combination_sum.java create mode 100644 expression_and_operator.java diff --git a/combination_sum.java b/combination_sum.java new file mode 100644 index 00000000..581cea3e --- /dev/null +++ b/combination_sum.java @@ -0,0 +1,57 @@ +//Time Complexity - O(n*2 ^ (m+n)) +//Space Complexity - O(n^2) +// class Solution { +// List> result; +// public List> combinationSum(int[] candidates, int target) { +// this.result= new ArrayList<>(); +// helper(candidates,target,new ArrayList<>(),0); +// return result; +// } +// private void helper(int[] candidates,int target, List path,int i){ +// //base +// if(target==0) { +// result.add(new ArrayList<>(path)); +// return; +// } +// if(target<0 || i==candidates.length) return; +// //logic +// //0 +// helper(candidates,target,new ArrayList<>(path),i+1); +// //action +// path.add(candidates[i]); +// // System.out.println(path); +// //1 +// //recurse +// helper(candidates,target-candidates[i],new ArrayList<>(path),i); +// } +// } + +//Time Complexity - O(2 ^ (m+n)) +//Space Complexity - O(n) +class Solution { + List> result; + public List> combinationSum(int[] candidates, int target) { + this.result= new ArrayList<>(); + helper(candidates,target,new ArrayList<>(),0); + return result; + } + private void helper(int[] candidates,int target, List path,int i){ + //base + if(target==0) { + result.add(new ArrayList<>(path)); + return; + } + if(target<0 || i==candidates.length) return; + //logic + //0 + helper(candidates,target,path,i+1); + //action + path.add(candidates[i]); + // System.out.println(path); + //1 + //recurse + helper(candidates,target-candidates[i],path,i); + //backtrack + path.remove(path.size()-1); + } +} \ No newline at end of file diff --git a/expression_and_operator.java b/expression_and_operator.java new file mode 100644 index 00000000..ff55e550 --- /dev/null +++ b/expression_and_operator.java @@ -0,0 +1,40 @@ +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){ + //base + if(pivot==num.length()) { + if(calc == target){ + result.add(path.toString()); + } + } + //logic + for(int i=pivot;i