您的位置:首页 > 其它

leetcode40 Combination Sum II

2015-11-22 16:21 381 查看
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]


Subscribe to see which companies asked this question
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
Arrays.sort(candidates);
/*for (int i = 0; i < candidates.length; i++) {
System.out.println(candidates[i]);
}*/
boolean[] used = new boolean[candidates.length];
Arrays.fill(used, false);
fun(candidates, 0, 0, target, new ArrayList<Integer>(), result, used);
return result;
}

private static void fun(int[] candidates, int start, int cur, int target, ArrayList<Integer> list,
List<List<Integer>> result, boolean[] used) {
if (cur > target)
return;
if (cur == target) {
//result.add(list);
List<Integer> tmp = new ArrayList<>(list);
if(!result.contains(tmp)){
result.add(tmp);
}
return;
}

for (int i = start; i < candidates.length; i++) {
if (!used[i]) {
ArrayList<Integer> temp = new ArrayList<Integer>(list);
temp.add(candidates[i]);
used[i] = true;
fun(candidates, i, cur + candidates[i], target, temp, result, used);
}
used[i] = false;
}
}

public static void main(String[] args) {
int[] candidate = { 10, 1, 2, 7, 6, 1, 5 };
List<List<Integer>> result = new Solution().combinationSum2(candidate, 8);
System.out.println(result.size());
for (int i = 0; i < result.size(); i++) {
for (int j = 0; j < result.get(i).size(); j++) {
System.out.print(result.get(i).get(j) + " ");
}
System.out.println();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: