【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);
相关推荐
2201_7578308710 小时前
全局异常处理器
java
aigcapi10 小时前
RAG 系统的黑盒测试:从算法对齐视角解析 GEO 优化的技术指标体系
大数据·人工智能·算法
知远同学11 小时前
Anaconda的安装使用(为python管理虚拟环境)
开发语言·python
苏宸啊11 小时前
链式二叉树基操代码实现&OJ题目
数据结构
小徐Chao努力11 小时前
【Langchain4j-Java AI开发】09-Agent智能体工作流
java·开发语言·人工智能
风筝在晴天搁浅11 小时前
hot100 25.K个一组翻转链表
数据结构·链表
CoderCodingNo12 小时前
【GESP】C++五级真题(贪心和剪枝思想) luogu-B3930 [GESP202312 五级] 烹饪问题
开发语言·c++·剪枝
柯慕灵12 小时前
7大推荐系统/算法框架对比
算法·推荐算法
adam-liu12 小时前
Fun Audio Chat 论文+项目调研
算法·语音端到端·fun-audio-chat
Coder_Boy_12 小时前
SpringAI与LangChain4j的智能应用-(理论篇3)
java·人工智能·spring boot·langchain