leetcode 39. 组合总和-java

题目所属分类

因为是求方案是什么 动态规划的话 求方案数会好些 但是求方案是什么动态规划用的时间复杂度 和爆搜差不多 所以直接dfs就可以 当作一道模板题来做
dfs搜索 比较不错的一道题

原题链接

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

代码案例:输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。

题解

dfs模板套用 比较不错的一道类似模板题
在这里插入图片描述
在这里插入图片描述

class Solution {
     List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        dfs(candidates,0,target);
        return res ;
    }
    public void dfs(int[] c , int u ,int target){
        if(target == 0){
            res.add(new ArrayList(path));
            return ;
        }
        if(u == c.length) return ;
        for(int i = 0 ; c[u] * i <= target ; i++){//假设选0个点 那么直接下一步dfs了
            dfs(c, u+1 , target-c[u] * i);
            path.add(c[u]);
        }
        //恢复现场
        for(int i = 0 ; c[u] * i <= target ; i++){
            path.remove(path.size()-1);
        }
    }
}
posted @   依嘫  阅读(33)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示