当前位置: 首页 > article >正文

LeetCode39- 组合总和

🔗:参考的题解:LeetCode39- 组合总和

class Solution {

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<Integer> path=new ArrayList<>();
        List<List<Integer>> paths=new ArrayList<>();
        Arrays.sort(candidates);//使用排序有利于剪枝
        dfs(candidates,0,paths,path,target);
        List<List<Integer>> res = new ArrayList(paths);
        return res;
    }
    public void dfs(int[] candidates , int begin, List<List<Integer>> paths ,List<Integer> path ,int num){
        if(num==0&&!path.isEmpty()){
            paths.add(new ArrayList<>(path));//这里必须使用深度复制
            return;
        }
		// i设置为begin起到了去重的作用,i=0的时候是搜索所有的路径
		//i=1的时候不会再次去搜索candidate[0]了,因为i=0的时候搜索过了,i=1就是从1开始搜索了!
		//i=1的搜索结果包含了i=0的搜索结果.
        for( int i = begin ; i<candidates.length;++i){
            int next_num = num-candidates[i];
            if(next_num<0){//剪枝的前提是数组有序!
                break;//这里直接break,continue会慢一些
            }
            path.add(candidates[i]);
            dfs(candidates,i,paths,path, next_num);
            if (!path.isEmpty()) {// remove Last element挪走最后一个元素!
                path.remove(path.size()-1);
            }

        }
    }

}

http://www.kler.cn/news/137278.html

相关文章:

  • 掌握深度学习利器——TensorFlow 2.x实战应用与进阶
  • scp rsync 软连接
  • linux控制台命令
  • OpenCV 中Mat.depth()的理解——每个像素的位数——每个像素中每个通道的精度
  • Qt中的tr函数
  • Java 基础面试题大概有哪些?
  • spring为什么要使用三级缓存来解决循环依赖
  • Java语言的特点||运算符
  • stack和queue简单实现(容器适配器)
  • mysql8 修改用户密码
  • 代码随想录二刷 | 链表 | 翻转链表
  • kolla 安装多节点openstack kolla部署openstack
  • 互联网医院源码搭建部署功能
  • k8s-pod管理 3
  • 怎么批量提取文件名字到Excel中?
  • 安装keras、tensorflow
  • flink 1.13.2的pom.xml文件模板
  • 数字化转型导师坚鹏:数字化时代银行网点厅堂营销5大难点分析
  • CAD文件转奥维 转shapefile
  • centos7卸载mongodb数据库