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

[LeetCode][Java] Combination Sum

2015-07-13 11:16 453 查看

题目:

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where
the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.


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
2,3,6,7
and target
7
,

A solution set is:

[7]


[2, 2, 3]


题意:

给定一组整数(C)和一个目标值 (T),从(C)中找出所有的存在且唯一的组合,使他们的和等于(T)。

同一个重复数字可以在C无限次的选择。

注意:

1.所有的数字包括目标值都是非负整数.

2. 组合中的元素(a1, a2,
… , ak)为升序排列。(ie, a1 ≤ a2 ≤
… ≤ ak).

3.最终的解中组合不能出现重复.

比如,给定一组整数集
2,3,6,7
和目标值
7
,

一个解集为:

[7]


[2, 2, 3]
.

算法分析:

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

AC代码:

/**
*  The first impression of this problem should be depth-first search(DFS). To solve DFS problem, recursion is a normal implementation.
*  Note that the candidates array is not sorted, we need to sort it first.
*/
public class Solution
{
List<List<Integer>> result;
List<Integer> solu;
public List<List<Integer>> combinationSum(int[] candidates, int target)
{
result = new ArrayList<>();
solu = new ArrayList<>();
if(candidates == null || candidates.length == 0) return result;
Arrays.sort(candidates);
getCombination(candidates, target, 0, 0);
return result;
}
public void getCombination(int[] candidates, int target, int sum, int level)
{
if(sum>target) return;
if(sum==target)
{
result.add(new ArrayList<>(solu));
return;
}
for(int i=level;i<candidates.length;i++)
{
sum+=candidates[i];
solu.add(candidates[i]);
getCombination(candidates, target, sum, i);
solu.remove(solu.size()-1);
sum-=candidates[i];
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: