【hot100-java】【组合总和】

R8-回溯篇

印象题,很基本的回溯

java 复制代码
class Solution {
    void backtrack(List<Integer> state,int target,int[] choices,int start,List<List<Integer>> ret){
        //子集和等于target,记录解
        if (target==0){
            ret.add(new ArrayList<>(state));
            return;
        }
        //遍历所有选择
        //剪枝2:从start开始遍历,避免生成重复子集
        for (int i=start;i<choices.length;i++){
            //剪枝1:若子集和超过target,直接结束循环
            if (target-choices[i]<0){
                break;
            }
            //做出选择,更新target
            state.add(choices[i]);
            //进行下一轮选择
            backtrack(state,target-choices[i],choices,i,ret);
            //回退:撤销选择,恢复到之前的状态
            state.remove(state.size()-1);
        }
    }
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        //状态子集
        List<Integer>state=new ArrayList<>();
        Arrays.sort(candidates);
        int start=0;
        //结果子集
        List<List<Integer>> ret=new ArrayList<>();
        backtrack(state,target,candidates,start,ret);
        return ret;
    }
}

PS:

java语法

1.移除数组最后一个元素

java 复制代码
state.remove(state.size()-1);

2.使用数组接受传入的参数值

java 复制代码
new ArrayList<>(state)

3.ret数组后面增加值

java 复制代码
ret.add()

4.数组排序,例如candidates是一个数组

java 复制代码
Arrays.sort(candidates);
相关推荐
shykevin26 分钟前
python开发Streamable HTTP MCP应用
开发语言·网络·python·网络协议·http
我不是程序猿儿29 分钟前
【C#】 lock 关键字
java·开发语言·c#
漫路在线1 小时前
JS逆向-某易云音乐下载器
开发语言·javascript·爬虫·python
先做个垃圾出来………1 小时前
哈夫曼树(Huffman Tree)
数据结构·算法
小辉懂编程1 小时前
C语言:51单片机实现数码管依次循环显示【1~F】课堂练习
c语言·开发语言·51单片机
tmacfrank2 小时前
网络编程中的直接内存与零拷贝
java·linux·网络
醍醐三叶2 小时前
C++类与对象--2 对象的初始化和清理
开发语言·c++
weixin_472339462 小时前
Maven 下载安装与配置教程
java·maven
Evaporator Core3 小时前
深入探索:Core Web Vitals 进阶优化与新兴指标
前端·windows
phoenix@Capricornus3 小时前
反向传播算法——矩阵形式递推公式——ReLU传递函数
算法·机器学习·矩阵