【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);
相关推荐
AD钙奶-lalala29 分钟前
Mac OS上搭建 http server
java
磊灬泽31 分钟前
【日常错误】鼠标无反应
linux·windows
luckys.one1 小时前
第9篇:Freqtrade量化交易之config.json 基础入门与初始化
javascript·数据库·python·mysql·算法·json·区块链
TomCode先生2 小时前
c#动态树形表达式详解
开发语言·c#
高-老师2 小时前
基于R语言的物种气候生态位动态量化与分布特征模拟
开发语言·r语言·物种气候
大翻哥哥2 小时前
Python 2025:量化金融与智能交易的新纪元
开发语言·python·金融
~|Bernard|2 小时前
在 PyCharm 里怎么“点鼠标”完成指令同样的运行操作
算法·conda
战术摸鱼大师3 小时前
电机控制(四)-级联PID控制器与参数整定(MATLAB&Simulink)
算法·matlab·运动控制·电机控制
Christo33 小时前
TFS-2018《On the convergence of the sparse possibilistic c-means algorithm》
人工智能·算法·机器学习·数据挖掘
weixin_437830943 小时前
使用冰狐智能辅助实现图形列表自动点击:OCR与HID技术详解
开发语言·javascript·ocr