搜索+剪枝,LeetCode 216. 组合总和 III

目录

一、题目

1、题目描述

2、接口描述

python3

cpp

3、原题链接

二、解题报告

1、思路分析

2、复杂度

3、代码详解

python3

cpp


一、题目

1、题目描述

找出所有相加之和为 nk个数的组合,且满足下列条件:

  • 只使用数字1到9
  • 每个数字 最多使用一次

返回 所有可能的有效组合的列表 。该列表不能包含相同的组合两次,组合可以以任何顺序返回。

2、接口描述

python3
复制代码
python 复制代码
class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
cpp
复制代码
cpp 复制代码
class Solution {
public:
    vector<vector<int>> combinationSum3(int k, int n) {

    }
};

3、原题链接

216. 组合总和 III


二、解题报告

1、思路分析

考虑暴搜,选或不选,这个很简单

然后考虑剪枝:

优化搜索顺序:优先选大的,这样路径少

可行性剪枝:

如果剩下的元素和加上当前元素和小于n,那么剪枝

如果剩下元素个数加上当前路径长度小于k,那么剪枝

2、复杂度

时间复杂度: 暴搜就不要管这个了 不会算 空间复杂度:emm

3、代码详解

python3
复制代码
python 复制代码
class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        ret = []
        path = []
        def dfs(cur: int, s: int) -> None:
            if not cur:
                if s == n and len(path) == k:
                    ret.append(path.copy())
                return
            if len(path) + cur < k:
                return
            if s + (cur + 1) * cur // 2 < n:
                return
            dfs(cur - 1, s)
            path.append(cur)
            dfs(cur - 1, s + cur)
            path.pop()
        dfs(9, 0)
        return ret
cpp
复制代码
cpp 复制代码
class Solution {
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<vector<int>> ret;
        vector<int> path;
        function<void(int, int)> dfs = [&](int cur, int s){
            if(!cur){
                if(s == n && path.size() == k) ret.emplace_back(path);
                return;
            }
            if(path.size() + cur < k) return;
            if(s + (cur + 1) * cur / 2 < n) return;
            dfs(cur - 1, s);
            path.emplace_back(cur);
            dfs(cur - 1, s + cur);
            path.pop_back();
        };
        dfs(9, 0);
        return ret;
    }
};
相关推荐
如竟没有火炬7 分钟前
至少有K个重复字符的最长子串
开发语言·数据结构·python·算法·leetcode·动态规划
想带你从多云到转晴18 分钟前
优选算法---双指针
java·算法
小O的算法实验室33 分钟前
2026年IEEE TSMC,基于Q学习平衡全局与局部搜索的防空资源分配问题进化算法,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
谙弆悕博士36 分钟前
快速学C语言——第17章:多文件编程与头文件规范
c语言·开发语言·算法·学习方法·头文件·多文件编程
水蓝烟雨1 小时前
2359. 找到离给定两个节点最近的节点
算法·leetcode
澈2071 小时前
哈希表:O(1)查找的终极指南
算法·哈希算法·散列表
幻奏岚音1 小时前
AI模型用户画像分析_new
人工智能·算法·计算机视觉·数据挖掘
阿Y加油吧1 小时前
二刷动态规划经典题:从打家劫舍到完全平方数,Java 实现复盘与优化
leetcode
阿Y加油吧2 小时前
二刷 LeetCode:爬楼梯与杨辉三角,Java 实现复盘
java·算法·leetcode
落羽的落羽2 小时前
【项目】C++从零实现JsonRpc框架——项目引入
linux·服务器·开发语言·c++·人工智能·算法·机器学习