【算法训练】非递归方式实现有重复元素求和

题目

给定一个无重复整型数组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;
    }
}

小结

递归方式的实现无非是依靠系统或者编程语言所依赖的执行机制,需要往深处入栈保留状态。而采用自己来进行栈的控制能够更好的确保程序的灵活性。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值