leetcode 39-Combination Sum(medium)
Given a set of candidate numbers (candidates
) (without duplicates) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
The same repeated number may be chosen from candidates
unlimited number of times.
Note:
- All numbers (including
target
- The solution set must not contain duplicate combinations.
backtracking
first sort the array, make it low to high
cases:
use a function:(a list to store all combinations, a tinylist store the trial at the moment, a int i store start place of numbers in candidates that we can add to the tinylist(the biggest index of number in tinylist) (avoid duplicates(permutaion))
1. target<0, return;
2. target=0, add tinylist to list and return;
3. start from i, iterate through i->end, everytime add one number to the tinylist, and continue backtracking, remember to remove the added one after backtracking
class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { List<List<Integer>> list=new ArrayList<>(); if(target==0||candidates.length==0) return list; Arrays.sort(candidates); findSum(candidates, list, new ArrayList<Integer>(), target, 0); return list; } public void findSum(int[] candidates, List<List<Integer>> list, List<Integer> tinyList, int target, int index){ if(target<0) return; else if(target==0){ list.add(new ArrayList<>(tinyList)); return; } for(int i=index;i<candidates.length;i++){ tinyList.add(candidates[i]); findSum(candidates, list, tinyList, target-candidates[i], i); tinyList.remove(tinyList.size()-1); } } }
leetcode 39-Combination Sum(medium)