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

leetCode练习(39)

2016-09-25 09:24 357 查看
题目:Combination Sum

难度:medium

问题描述:

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.
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]
]


解题思路:前面出现过固定的4数和、3数和等于定值的题目,现在出现了更一般的题目,即不定长和等于定值。当然了,对于前面题目熟悉的同学一定很容易想到使用backtracking方法。使用回溯法,在此题中要注意两点,一是给定的数组要是【2,2,3】这种带重复的情况,我们通过if(nums[I]==nums[I-1])来判断此时调用的‘2’前面是否已经调用过(包含前面一个2的所有可能一定包含了含有后面一个2的所有可能)。二是本题,一个nums[I]可以重复多次,因此迭代时的起始位置不是下一个数,而是i本身。
具体代码如下:

[code]public class m_39_CombinationSum {
ArrayList list=new ArrayList();
public List combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
int len=candidates.length;
if(target=nums.length) return;
if(nums[index]>target) return;
for(int i=index;i0&&nums[i]==nums[i-1]){
continue;
}
ArrayList temp=(ArrayList)alist.clone();
temp.add(nums[i]);
// show(temp);
if(nums[i]==target){
//show(temp);
list.add(temp);
return;
}else{
backtracking(nums,i,target-nums[i],temp);
}
}
}
public void show(List list){
System.out.println();
for(int i=0;i
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息