https://oj.leetcode.com/problems/combination-sum-ii/
http://blog.csdn.net/linhuanmars/article/details/20829099
public class Solution {
public List<List<Integer>> combinationSum2(int[] num, int target)
{
if (num == null || num.length == 0)
return Collections.emptyList();
// Sort
Arrays.sort(num);
Set<List<Integer>> result = new HashSet<>();
sum(num, target, 0, new ArrayList<Integer>(), result);
return new ArrayList<List<Integer>>(result);
}
private void sum(int[] num, int t, int start, List<Integer> curnums, Set<List<Integer>> result)
{
if (t < 0)
return;
if (t == 0)
{
List<Integer> r = new ArrayList<>(curnums);
Collections.sort(r);
result.add(r);
return;
}
for (int i = start ; i < num.length ; i ++)
{
curnums.add(num[i]);
// 由于每个数字只能被用到以此,所以 nextstart = i + 1
// 这是和 combination sum 问题的区别
// 而且,这导致了结果集有可能有重复
// 比如 输入数组有两个2
// 一个结果了使用 第一个2
// 另一个结果使用了 第二个2
// 需要使用set去除重复
int nextstart = i + 1;
sum(num, t - num[i], i + 1, curnums, result);
curnums.remove(curnums.size() - 1);
}
}
}[LeetCode]40 Combination Sum II
原文地址:http://7371901.blog.51cto.com/7361901/1598590