diff --git a/CombinationSum.java b/CombinationSum.java new file mode 100644 index 00000000..cb10484c --- /dev/null +++ b/CombinationSum.java @@ -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> res; + public List> combinationSum(int[] candidates, int target) { + this.res = new ArrayList<>(); + List path = new ArrayList<>(); + helper(candidates, 0, path, target); + return res; + } + + private void helper(int[] candidates, int idx, List 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); + } +} \ No newline at end of file diff --git a/Subsets.java b/Subsets.java new file mode 100644 index 00000000..9a65494c --- /dev/null +++ b/Subsets.java @@ -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> res; + public List> subsets(int[] nums) { + this.res = new ArrayList<>(); + List path = new ArrayList<>(); + helper(nums, path, 0); + return res; + } + + private void helper(int[] nums, List 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); + } +} \ No newline at end of file