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

Combination Sum | Java最短代码实现

2016-03-15 17:37 501 查看
原题链接:39. Combination Sum
拓展博文:Combination Sum II | Java最短代码实现
【思路】

基本思路是先排好序,然后每次递归中把剩下的元素一一加到结果集合中,并且把目标减去加入的元素,然后把剩下元素(包括当前加入的元素)放到下一层递归中解决子问题。算法复杂度因为是NP问题,所以自然是指数量级的:

public List<List<Integer>> combinationSum(int[] candidates, int target) {
ArrayList<List<Integer>> result = new ArrayList<List<Integer>>();
Arrays.sort(candidates);
ArrayList<Integer> tmp = new ArrayList<Integer>();
findCandidates(candidates, target, 0, tmp, result);
return result;
}

public void findCandidates(int[] candidates, int target, int curIndex, ArrayList<Integer> tmp, ArrayList<List<Integer>> result) {
if (target == 0)
result.add(new ArrayList<Integer>(tmp));
for (int i = curIndex; i < candidates.length && target >= candidates[i]; i++) {
tmp.add(candidates[i]);
findCandidates(candidates, target - candidates[i], i, tmp, result);
tmp.remove(new Integer(candidates[i]));
}
}
168 / 168 test
cases passed. Runtime: 7
ms Your runtime beats 57.38% of javasubmissions.

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