2024.4.20力扣每日一题——组合总和

题目来源

力扣每日一题;题序:39

我的题解

方法一 回溯

以每一个位置开始深搜,直到target等于0或者小于0或者遍历完结束。
关键在于:注意去重 巧妙方法:传入一个index,是上一次遍历元素的位置,控制其不再去遍历前面的元素

时间复杂度:O( n ∗ 2 n n*2^n n2n)。n 个位置每次考虑选或者不选,如果符合条件,就加入答案的时间代价。但是实际运行的时候,因为不可能所有的解都满足条件,递归的时候还会用 target−candidates[idx]≥0进行剪枝,所以实际运行情况是远远小于这个时间复杂度的。
空间复杂度:O(n)

class Solution {
    List<List<Integer>> res;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        res=new ArrayList<>();
        List<Integer> path=new ArrayList<>();
        for(int i=0;i<candidates.length;i++){
            path.add(candidates[i]);
            dfs(candidates,target-candidates[i],i,path);
            path.remove(path.size()-1);
        }
        return res;

    }

    public void dfs(int[] candidates,int target,int index,List<Integer> path){
        if(target==0)
            res.add(new ArrayList<>(path));
        //后一个条件的前提是candidates数组是升序的,这里是看了官方的题解,感觉默认是有序的
        if(target<0||target-candidates[index]<0)
            return ;
        for(int next=index;next<candidates.length;next++){
            path.add(candidates[next]);
            dfs(candidates,target-candidates[next],next,path);
            path.remove(path.size()-1);
        }
    }
}

有任何问题,欢迎评论区交流,欢迎评论区提供其它解题思路(代码),也可以点个赞支持一下作者哈😄~

相关推荐

  1. 2024.4.20每日——组合总和

    2024-04-21 03:56:02       35 阅读
  2. 2024.4.22每日——组合总和

    2024-04-21 03:56:02       25 阅读
  3. 2024.4.21每日——组合总和 III

    2024-04-21 03:56:02       32 阅读
  4. 每日

    2024-04-21 03:56:02       38 阅读
  5. 每日40:组和总数||

    2024-04-21 03:56:02       32 阅读
  6. 每日:课程表Ⅱ

    2024-04-21 03:56:02       68 阅读
  7. 每日 6/6

    2024-04-21 03:56:02       35 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-21 03:56:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-21 03:56:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-21 03:56:02       82 阅读
  4. Python语言-面向对象

    2024-04-21 03:56:02       91 阅读

热门阅读

  1. 游戏中的伤害类型

    2024-04-21 03:56:02       40 阅读
  2. 正则表达式大全,30个正则表达式详细案例

    2024-04-21 03:56:02       40 阅读
  3. 上海计算机学会2023年12月月赛C++丙组T2移动复位

    2024-04-21 03:56:02       41 阅读
  4. 搭建vue3组件库(一):Monorepo项目搭建

    2024-04-21 03:56:02       37 阅读
  5. Docker常见命令学习

    2024-04-21 03:56:02       37 阅读
  6. mac修改/etc/profile导致终端所有命令不可使用

    2024-04-21 03:56:02       39 阅读
  7. CentOS系统上经常使用的一些基本命令

    2024-04-21 03:56:02       37 阅读
  8. android11启动服务

    2024-04-21 03:56:02       39 阅读