【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);
相关推荐
ん贤2 小时前
Go channel 深入解析
开发语言·后端·golang
夜天炫安全3 小时前
数据结构中所需的C语言基础
c语言·数据结构·算法
2301_789015624 小时前
DS进阶:AVL树
开发语言·数据结构·c++·算法
曹牧4 小时前
BeanUtils.copyProperties‌
java
QWQ___qwq5 小时前
Java线程安全深度总结:基本类型与引用类型的本质区别
java·安全·面试
Filotimo_5 小时前
5.3 Internet基础知识
开发语言·php
识君啊5 小时前
Java异常处理:中小厂面试通关指南
java·开发语言·面试·异常处理·exception·中小厂
zyq99101_17 小时前
优化二分查找:前缀和降复杂度
数据结构·python·蓝桥杯
qyzm7 小时前
天梯赛练习(3月13日)
开发语言·数据结构·python·算法·贪心算法
月月玩代码7 小时前
Actuator,Spring Boot应用监控与管理端点!
java·spring boot·后端