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]
z这道题是根据给定的数组和target,算出数组中数字之和满足target的元素,元素可以重复出现。
用的是回朔法。
回朔法就是要用stack来模拟。
具体思路如下:
1. 对给定数组 candidtas[]进行排序。
2. 对candidates[]元素从大到小遍历,得到candidtates[i]
3.
if(candidates[i]+sum==target){
stack.push(i);
//Stack tobeadd=(Stack<Integer>) stack1.clone ();
listtmp.add((Stack<Integer>) stack.clone ());
stack.pop();
i--;
}
else if(candidates[i]+sum>target){
i--;
}
else if(candidates[i]+sum<target){
sum+=candidates[i];
stack.push(i);
}就是如果和满足target,那么加入结果集,并且弹出stack顶的元素,并且i--,寻找下一个由更小元素组成的可能。
如果和大于target,那么就弹出stack顶元素,并且i--,寻找下一个由更小元素组成的可能。
如果和小于target,那么就继续把当前元素压栈。重复以上循环。
这里面有一个判断条件,就是如果--i<0。并且!stack.isEmpty();说明在当前stack情况下试了更小元素的所有可能,都不满足,那么,就需要把satck中元素继续弹出来,加入更小的元素进去。
上代码
import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Combination_Sum {
public static List<List<Integer>> combinationSum(int[] candidates, int target) {
Stack<Integer> stack=new Stack<>();
List<Stack<Integer>> listtmp=new ArrayList<>();
//List<List<Map<Integer, Integer>>> resultList=new ArrayList<>();
int sum=0;
for(int i=candidates.length-1;i>=0||!stack.isEmpty();){
if(i<0){
if(stack.isEmpty())break;
i=stack.pop();
sum-=candidates[i];
i--;
continue;
}
if(candidates[i]+sum==target){
stack.push(i);
//Stack tobeadd=(Stack<Integer>) stack1.clone ();
listtmp.add((Stack<Integer>) stack.clone ());
stack.pop();
i--;
}
else
if(candidates[i]+sum>target){
i--;
}
else
if(candidates[i]+sum<target){
sum+=candidates[i];
stack.push(i);
}
}
List<List<Integer>> result=new ArrayList<>();
for (Stack<Integer> keyarray : listtmp) {
List<Integer> childIntegers=new ArrayList<>();
for(Integer key:keyarray){
childIntegers.add(0,candidates[key]);
}
result.add(childIntegers);
}
return result;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] candidates={1,2};
int target=4;
combinationSum(candidates, target);
}
}
本文介绍了一种使用回溯法解决组合求和问题的方法。针对给定数组和目标值,找出数组中所有可能的组合,使得这些组合的元素之和等于目标值。文章详细解释了算法的具体实现过程,并附带了完整的Java代码示例。
151

被折叠的 条评论
为什么被折叠?



