ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

2021.11.25 - SX08-07.组合总和

2021-11-25 18:31:27  阅读:15  来源: 互联网

标签:25 2021.11 target int res private candidates stack SX08


文章目录

1. 题目

在这里插入图片描述

2. 思路

(1) 回溯法

  • 首先将数组进行排序,然后可以将剪枝策略放到for循环中,当路径之和已经大于目标值时,直接返回即可,这样可以节省大量入栈出栈的时间。

3. 代码

import java.util.*;

public class Test {
    public static void main(String[] args) {
    }
}

class Solution {
    private List<List<Integer>> res;
    private LinkedList<Integer> stack;
    private int[] candidates;
    private int target;

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        res = new ArrayList<>();
        stack = new LinkedList<>();
        this.candidates = candidates;
        this.target = target;
        Arrays.sort(candidates);
        backtrack(0, 0);
        return res;
    }

    private void backtrack(int index, int sum) {
        if (sum == target) {
            res.add(new ArrayList<>(stack));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            int next = sum + candidates[i];
            if (next > target) {
                return;
            }
            stack.addLast(candidates[i]);
            backtrack(i, next);
            stack.removeLast();
        }
    }
}

标签:25,2021.11,target,int,res,private,candidates,stack,SX08
来源: https://blog.csdn.net/qq_44021223/article/details/121544256

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有