题目
给定一个无重复整型数组candidates和一个目标整数target,返回一个唯一candtitions的组合,让被选择的元素之和等于target。
条件:同一个元素可重复选择示例
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
分析
这个算法题有很多种解法,通常会想到的就是采用回溯方法来解。通过确定退出条件和一些剪枝条件控制就能得到最后的结果,网上很容易能够找到现成的代码。但是,如何自己通过使用栈来实现采用递归方式的栈实现过程呢?
代码
class Solution {
private static int getTop(int[] candidates, int e){
if(candidates.length == 0) return 0;
for(int i = 0; i < candidates.length; i++){
if(e == candidates[i]){
return i;
}
}
return 0;
}
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList(new ArrayList<Integer>());
Stack<Integer> stack = new Stack<Integer>();
int len = candidates.length;
if(len < 1 || len > 30) return result;
int start = 0;
int idx = 0;
int remain = target;
int cnt = 0;
while(start < len){
if(idx < len && 0 < remain){
stack.push(candidates[idx]);
remain -= candidates[idx];
if(remain == 0){
List<Integer> aSolution = new ArrayList<Integer>();
Iterator<Integer> itr = stack.iterator();
while (itr.hasNext()) {
aSolution.add(itr.next());
}
result.add(aSolution);
Integer last = stack.pop();
remain += last;
idx++;
}
}else{
if(idx >= len && remain >0){
Integer last1 = stack.pop();
remain += last1;
int top = getTop(candidates, last1);
idx = top + 1;
}else if(idx >= len && remain <0){
Integer last1 = stack.pop();
remain += last1;
int top = getTop(candidates, last1);
idx = top + 1;
}else if(idx < len && remain < 0){
Integer last = stack.pop();
remain += last;
idx++;
}else{
idx++;
}
}
if(stack.empty()){
start++;
idx = start;
}
}
return result;
}
}
小结
递归方式的实现无非是依靠系统或者编程语言所依赖的执行机制,需要往深处入栈保留状态。而采用自己来进行栈的控制能够更好的确保程序的灵活性。