Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions CombinationSum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* Approach1: The problem is similar to coin change. So go exhaustive and explore all options
- The idea is to do a 0/1 recursion -> choose/not choose
- TC: O(2^m+n) -> two input variables, candidates of length n and target
- SC: O(n) -> path array
*/
class Solution {
List<List<Integer>> res;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
this.res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
helper(candidates, 0, path, target);
return res;
}

private void helper(int[] candidates, int idx, List<Integer> path, int target){
//base
// if we have selected more candidates then required or idx goes out of bound
if(target < 0 || idx >= candidates.length)
return;

//once we have a combination that is equal to the target, add that to the result
if(target == 0){
//create a deep copy of the path before adding it to the result as we are using the same reference of the path
res.add(new ArrayList<>(path));
return;
}

//logic

//0-> not choose
helper(candidates, idx + 1, path, target);
//1-> choose

//add element in the path

//action
path.add(candidates[idx]);
//recurse
helper(candidates, idx, path, target - candidates[idx]);
//backtrack
path.remove(path.size() - 1);
}
}
36 changes: 36 additions & 0 deletions Subsets.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Approach:
- The idea is to use 0/1 recursion to explore all subsets of the array
- Once we have reached the end, add it to the result
-TC: O(2^n * n)-> n for copying the path to the resultant array * choose/not choose for n elements so 2^n
- SC: O(n) -> recursion stack space
*/
class Solution {
List<List<Integer>> res;
public List<List<Integer>> subsets(int[] nums) {
this.res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
helper(nums, path, 0);
return res;
}

private void helper(int[] nums, List<Integer> path, int idx){
//base
if(idx == nums.length){
res.add(new ArrayList<>(path));
return;
}
//logic

//not choose
helper(nums, path, idx + 1);
//choose
//action
path.add(nums[idx]);

//recurse
helper(nums, path, idx + 1);
//backtrack
path.remove(path.size() - 1);
}
}