您的位置:首页 > 其它

[LeetCode] Combination Sum II

2014-04-30 17:57 429 查看
Total Accepted: 7633 Total
Submissions: 31949

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]
 public class Solution {
public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> path = new ArrayList<Integer>();

Arrays.sort(num);

dfs(num, list, path, 0, target);

return list;
}

public void dfs(int[] num, ArrayList<ArrayList<Integer>> list,
ArrayList<Integer> path, int index, int target) {
if (target == 0) {
list.add(new ArrayList<Integer>(path));
return;
}

for (int i = index; i < num.length; i++) {
if (num[i] > target) break;

path.add(num[i]);
dfs(num, list, path, i + 1, target - num[i]);
path.remove(path.size() - 1);
// skip repeated numbers
while (i < num.length - 1 && num[i+1] == num[i]) i++;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode Recursion DFS