您的位置:首页 > 其它

【Leetcode】Combination Sum II

2015-11-28 15:54 337 查看
题目链接:https://leetcode.com/problems/combination-sum-ii/

题目:

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]


思路:
candidate set每个元素只允许选择一次。因为set中可能会有重复的元素导致solution set中可能会有重复解,比如sum=8,candidate set[1,1,7],就有两个[1,7]解。每个元素只选择一次,可以在Combination
Sum 中改为 dspCombination(sum, i+1);,为了解决重复解的问题,我们引入HashSet保存解,最后在将hashSet转为List返回就好了。
算法:

int cl[] = null;
List<List<Integer>> iLists = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
HashSet<ArrayList<Integer>> sets = new HashSet<ArrayList<Integer>>();
int target = 0;

public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
this.cl = candidates;
this.target = target;
dspCombination2(0, 0);
iLists.addAll(sets);  //HashSet 转为 List
return iLists;
}

private void dspCombination2(int sum, int level) {
if (sum == target) {
sets.add(new ArrayList<Integer>(list)); //用HashSet保存解
return;
} else if (sum > target) {
return;
} else {
for (int i = level; i < cl.length; i++) {
sum += cl[i];
list.add(cl[i]);
dspCombination2(sum, i + 1); //每个元素只允许选择一次
list.remove(list.size() - 1);
sum -= cl[i];
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: