【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);
相关推荐
m0_738755929 分钟前
.ideavimrc在idea打不开
java·vim·intellij-idea
超级小的大杯柠檬水10 分钟前
IDEA中实现springboot热部署
java·spring boot·intellij-idea
Ace'10 分钟前
蓝桥杯15届C/C++B组省赛题目
数据结构·算法·蓝桥杯
1 ‍♂️‍️11 分钟前
链表(3)链表的基本操作
数据结构·链表
攀小黑14 分钟前
IDEA 24.1 could not autowire. No beans of ‘***‘ type found. 取消 某个类型的 警告
java·ide·intellij-idea
腊笔不小新xingo23 分钟前
READONLY You can‘t write against a read only replica
java·redis·bootstrap
JavaGuide31 分钟前
一条 SQL 语句在 MySQL 中是如何执行的?
java·数据库·后端·mysql
andyleung52038 分钟前
murmur 算法
算法
阿华的代码王国40 分钟前
【JavaEE】——多线程(join阻塞,计算,引用,状态)
java·开发语言·数据结构·java-ee
江喜原1 小时前
微服务下设计一个注解标识是否需要登录
java·微服务·架构·登录