Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
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 10,1,2,7,6,1,5
and target 8
,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
题意:给出一个数组(数组中可能有重复的数)和一个目标数,求其构成目标数的所有组合
思路:由于数组中有重复,需要有一个数组记录原数组中不同的数及相应的数在原来数组中出现的次数。在递归过程中,结束条件是当前记录的总数和等于目标数就退出。如果当前选择的数的计数非0,就选择该数,同时记录当前所选择的数的总和,继续递归。
代码如下:
class Solution
{
private void __combinationSum2(int[] candidates, int start, int cursum, int total, Map<Integer, Integer> map, List<Integer> arr, List<List<Integer>> ans)
{
if (cursum == total)
{
List<Integer> tmp = new ArrayList<Integer>();
tmp.addAll(arr);
ans.add(tmp);
return;
}
for (int i = start; i < candidates.length; i++)
{
int c = map.get(candidates[i]);
if (c > 0)
{
if (cursum + candidates[i] > total) return;
arr.add(candidates[i]);
int len = arr.size();
map.put(candidates[i], c - 1);
__combinationSum2(candidates, i, cursum + candidates[i], total, map, arr, ans);
arr.remove(len - 1);
map.put(candidates[i], c);
}
}
}
public List<List<Integer>> combinationSum2(int[] candidates, int target)
{
Arrays.sort(candidates);
List<Integer> arr = new ArrayList<Integer>();
List<List<Integer>> ans = new ArrayList<List<Integer>>();
Map<Integer, Integer> map = new TreeMap<Integer, Integer>();
for (int num : candidates)
{
if (map.containsKey(num))
{
map.put(num, map.get(num) + 1);
}
else {
map.put(num, 1);
}
}
int[] cand = new int[map.size()];
int c = 0;
for (Integer k : map.keySet())
{
cand[c++] = k;
}
__combinationSum2(cand, 0, 0, target, map, arr, ans);
return ans;
}
}