diff --git a/Leetcode_282.java b/Leetcode_282.java new file mode 100644 index 00000000..095638f4 --- /dev/null +++ b/Leetcode_282.java @@ -0,0 +1,112 @@ +//Way1 +//Generate all possible numbers +//Apply all possible combinations +//Once last index is reached, check whether target is made or not +//If equals to target, add to result +//TC: O(4ⁿ * n +//SC: n^2 +class Solution { + List result; + public List addOperators(String num, int target) { + this.result=new ArrayList<>(); + helper(num,0,0,0,"",target); + return result; + + } + + private void helper(String num, int pivot, long calc, long prev, String path, int target){ + // + if(pivot==num.length()){ + if(calc==target){ + result.add(path); + return; + } + } + + + + for(int i=pivot;i result; + public List addOperators(String num, int target) { + this.result=new ArrayList<>(); + helper(num,0,0,0,new StringBuilder(),target); + return result; + + } + + private void helper(String num, int pivot, long calc, long prev, StringBuilder path, int target){ + // + if(pivot==num.length()){ + if(calc==target){ + result.add(path.toString()); + return; + } + } + + + + for(int i=pivot;i> combinationSum(int[] candidates, int target) { + List> res=new ArrayList<>(); + dfs(candidates,0,target,new ArrayList<>(),res); + return res; + + } + private void dfs(int[] candidates, int i, int target, List path, List> result){ + //base case + if(target<0 || i==candidates.length){ + return; + } + + if(target==0){ + result.add(new ArrayList<>(path)); + return; + } + + + //actual logic + //no choose + dfs(candidates,i+1,target,path,result); + + //choose + path.add(candidates[i]); + dfs(candidates,i,target-candidates[i],path,result); + //backtrack + path.remove(path.size()-1); + } +} + + +//way2 +//for loop based recurssion - with backtracking +//in for loop - start with i=0 +//call with same i=0 till target becomes to negative +//Once target = 0, add the path to result +//And when iteration returned, new one will start with i+1 +//process goes on +//TC: O(n * 2^(m+n)) where m is the candidates length and n is the target +//SC: O(n * h) -> O(n^2) +class Solution { + public List> combinationSum(int[] candidates, int target) { + List> ans = new ArrayList<>(); + helper(candidates,0,target,new ArrayList<>(),ans); + return ans; + + } + private void helper(int[] candidates, int pivot, int target,List path, List> ans){ + if(target<0){ + return; + } + if(target==0){ + ans.add(new ArrayList<>(path)); + } + + for(int i=pivot;i