39. 组合总和

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


注意几点:
1,关于索引参数,由于是可以重复取值,那么传给下一层的就是和本层同位置索引

    // 考虑到不满足是要回溯吐出这个数。所以使用stack
    Stack<Integer> stack = new Stack<>();
    List<List<Integer>> ret = new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        dfs(candidates,0,target);
        return ret;

    }
    // index是开始位置索引
    public void dfs(int[] candidates, int index, int target) {
        // 不满足,直接返回
        if(target < 0) {
            return;
        }
        // 已经满足条件了,返回了
        if(target == 0) {
            ret.add(new ArrayList<>(stack));
            return;
        }
        // 由于可以取重复的值,所以传入的是i,保证下一层和本层开始的索引是一致的,这样可以保证可以取重复的值.
        for(int i=index;i<candidates.length;i++) {
            stack.push(candidates[i]);
            dfs(candidates,i,target-candidates[i]);
            stack.pop();
        }
    }

posted @ 2022-02-28 13:53  一颗青菜  阅读(2)  评论(0)    收藏  举报