leetcode : comobination sum [经典回溯]
Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
- All numbers (including target) will be positive integers.
- The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[ [7], [2, 2, 3] ]
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(candidates == null || candidates.length == 0) {
return result;
}
List<Integer> list = new ArrayList<Integer>();
Arrays.sort(candidates);
helper(result, list, candidates, target, 0);
return result;
}
public void helper(List<List<Integer>> result, List<Integer> list, int[] nums, int remains, int position) {
if(remains < 0) {
return;
}
if(remains == 0) {
result.add(new ArrayList<Integer>(list));
}
for(int i = position; i < nums.length; i++) {
list.add(nums[i]);
helper(result, list, nums, remains - nums[i],i);
list.remove(list.size() - 1);
}
}
}
浙公网安备 33010602011771号