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
,
[ [7], [2, 2, 3]]
public class Solution { public List
> combinationSum(int[] candidates, int target) { List
> result = new ArrayList
>(); if(candidates == null || candidates.length == 0) { return result; } List list = new ArrayList (); Arrays.sort(candidates); helper(result, list, candidates, target, 0); return result; } public void helper(List
> result, List list, int[] nums, int remains, int position) { if(remains < 0) { return; } if(remains == 0) { result.add(new ArrayList (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); } } }