Leetcode 39 组合总和

题意理解:

        一个 无重复元素 的整数数组 candidates 和一个目标整数 target    

        从candidates 取数字,使其和== target ,有多少种组合(candidates 中的 同一个 数字可以 无限制重复被选取

        这道题和之前一道组合的区别:这道题允许重复的数字

解题思路

        组合问题——>递归

        这道题特殊的地方,对组合内数字的和做了要求,而不是个数,一开始并不确定树的深度,组合的大小是不定的。

1.暴力回溯+剪枝优化

class Solution {
    List<List<Integer>> result=new ArrayList<>();
    LinkedList<Integer> path=new LinkedList<>();
    int sum=0;

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        backtracking(candidates,target,0);
        return result;
    }

    public void backtracking(int[] candidates,int target,int index){
        //结果收集
        if(sum==target){
            result.add(new ArrayList<>(path));
            return;
        } else if (sum>target) {//剪枝
            return;
        }
        //遍历分支
        for(int i=index;i<candidates.length;i++){
            path.add(candidates[i]);
            sum+=candidates[i];
            //递归
            backtracking(candidates,target,i);
            //回溯
            path.removeLast();
            sum-=candidates[i];
        }
    }
}

2.分析

时间复杂度:O(n\times 2^{n})

        n个位置,每个位置有两种可能选或不选。

        时间复杂度和树的深度有关,是所有可行解之和

空间复杂度:O(n)

相关推荐

  1. 【回溯】Leetcode 39. 组合总和【中等】

    2023-12-10 05:44:03       43 阅读

最近更新

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

    2023-12-10 05:44:03       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-10 05:44:03       106 阅读
  3. 在Django里面运行非项目文件

    2023-12-10 05:44:03       87 阅读
  4. Python语言-面向对象

    2023-12-10 05:44:03       96 阅读

热门阅读

  1. xtu oj 1233 Cycle Matrix

    2023-12-10 05:44:03       58 阅读
  2. 在 MySQL 中创建用户和分配权限

    2023-12-10 05:44:03       50 阅读
  3. 力扣:197. 上升的温度(Python3)

    2023-12-10 05:44:03       61 阅读
  4. 网络规划的组成

    2023-12-10 05:44:03       51 阅读
  5. [LeetCode] 15. 三数之和

    2023-12-10 05:44:03       63 阅读
  6. 如何安装和使用three.js

    2023-12-10 05:44:03       51 阅读
  7. Git:版本控制的艺术与实践

    2023-12-10 05:44:03       57 阅读
  8. RUST博客帖子编辑示例

    2023-12-10 05:44:03       50 阅读
  9. MySQL库与表的备份

    2023-12-10 05:44:03       57 阅读
  10. HJ94 记票统计

    2023-12-10 05:44:03       69 阅读
  11. nvue页面用法uniapp

    2023-12-10 05:44:03       61 阅读