您的位置:首页 > 编程语言 > Java开发

Leet Code 40 - Combination Sum II - 组合和 - Java

2016-06-21 00:00 459 查看
摘要: Leet Code 40 - Combination Sum II - 组合和 - Java

问题原始链接 https://leetcode.com/problems/combination-sum-ii

给定一个数集C和一个目标数T,找到C中所有和等于T的组合。C中的每个数在组合中最大只允许使用一次。

注意:

所有的数(包括目标数)都是正整数。

结果中不允许有重复组合。

例如,给定数集 [10,1,2,7,6,1,5],目标数8

[
[1,7]
[1,2,5]
[2,6]
[1,1,6]
]

public class Solution {
public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (candidates == null || candidates.length == 0) {
return result;
}
Arrays.sort(candidates);
List<Integer> temp = new ArrayList<Integer>();
Map<Integer, Integer> count = count(candidates);
combinationSum(candidates, target, count, candidates.length - 1, temp,
result);
return result;
}

private static Map<Integer, Integer> count(int[] candidates) {
Map<Integer, Integer> result = new HashMap<Integer, Integer>();
for (Integer i : candidates) {
Integer c = result.get(i);
result.put(i, c == null ? Integer.valueOf(1) : (c + 1));
}
return result;
}

private static void combinationSum(int[] candidates, int target,
Map<Integer, Integer> count, int i, List<Integer> temp,
List<List<Integer>> result) {
int c = count.get(candidates[i]);
for (int j = Math.min(target / candidates[i], c); j >= 0; j--) {
if (i == 0) {
if (target == candidates[i] * j) {
result.add(add(temp, candidates[i], j));
}
} else {
List<Integer> t = add(temp, candidates[i], j);
if (target == j * candidates[i]) {
result.add(t);
} else {
int k = i - c;
if (k >= 0) {
combinationSum(candidates, target - j * candidates[i], count, k, t,
result);
}
}
}
}
}

private static List<Integer> add(List<Integer> temp, int x, int j) {
List<Integer> t = new ArrayList<Integer>(temp);
for (int k = 0; k < j; k++) {
t.add(x);
}
return t;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息