diff --git a/CombinationSum.java b/CombinationSum.java new file mode 100644 index 00000000..3ce34791 --- /dev/null +++ b/CombinationSum.java @@ -0,0 +1,28 @@ +import java.util.ArrayList; +import java.util.List; + +public class CombinationSum { + public List> combinationSum(int[] candidates, int target) { + List> result = new ArrayList<>(); + List set = new ArrayList<>(); + helper(candidates, target, 0, result, set); + return result; + } + + private void helper(int[] candidates, int target, int idx, List> result, List set){ + //base + if(idx==candidates.length || target < 0) return; + if(target==0){ + result.add( new ArrayList<>(set)); + return; + } + //logic + //choose + set.add(candidates[idx]); + helper(candidates, target-candidates[idx], idx, result, set); + //backtracking + set.remove(set.size()-1); + //no choose + helper(candidates, target, idx+1, result, set); + } +}