Given a set of candidate numbers (C) 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.
- Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
- 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]
题意:给出一个集合和一个目标数,求可以构成目标数的所有子集
思路:属于组合问题,将数组从小到大排序,然后依次填入选择的数,如果当前计算的和大于目标数,就不继续。如果相等,将结果记录。如果小于,选择当前数,继续递归
代码如下:
class Solution
{
private void __combination(int[] candidates, int start, int cursum, int target, List<Integer> arr, List<List<Integer>> ans)
{
if (cursum == target)
{
ArrayList<Integer> tmp = new ArrayList<Integer>();
for (Integer a : arr)
{
tmp.add(a);
}
ans.add(tmp);
return;
}
for (int i = start; i < candidates.length; i++)
{
if (cursum + candidates[i] > target) return;
arr.add(candidates[i]);
int len = arr.size();
__combination(candidates, i, cursum + candidates[i], target, arr, ans);
arr.remove(len - 1);
}
}
public List<List<Integer>> combinationSum(int[] candidates, int target)
{
Arrays.sort(candidates);
List<List<Integer>> ans = new ArrayList<List<Integer>>();
List<Integer> arr = new ArrayList<Integer>();
__combination(candidates, 0, 0, target, arr, ans);
return ans;
}
}