LeetCode:组合求和III之回溯法

题目

题目链接

markdown 复制代码
找出所有相加之和为 n 的 k 个数的组合,且满足下列条件:

只使用数字1到9
每个数字 最多使用一次 
返回 所有可能的有效组合的列表 。该列表不能包含相同的组合两次,组合可以以任何顺序返回。

题目图解

**

**

cpp代码

cpp 复制代码
class Solution {
public:
    vector<int> nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    //回溯
    void dfs(vector<vector<int>>& ans, vector<int>& path, int k, int target, int idx)
    {
        if (path.size() == k && target != 0)
            return;

        if (target == 0 && path.size() == k)
        {
            ans.push_back(path);
            return;
        }

        for (int i = idx; i < nums.size(); ++i)
        {
            //剪枝:如果当前的值不满足条件,则后面的数字就没有必要继续了
            if (target - nums[i] < 0)
            {
                break;
            }
            path.push_back(nums[i]);
            dfs(ans, path, k, target - nums[i], i + 1);
            //回溯
            path.pop_back();
        }
    }

    vector<vector<int>> combinationSum3(int k, int n)
    {
        vector<vector<int>> ans;
        vector<int> path;
        dfs(ans, path, k, n, 0);
        return ans;
    }
};
相关推荐
文丑颜不良啊1 天前
LeetCode3041~3060题目解析
java·leetcode
eggwyw1 天前
C++ union 的一种妙用法
开发语言·c++
罗西的思考1 天前
【轻量化复现大模型 / KIMI K3】MTP / EAGLE‑3 模块交互式演示
人工智能·深度学习·算法
文丑颜不良啊1 天前
LeetCode3101~3120题目解析
java·leetcode
ShineWinsu1 天前
对于Qt:QHBoxLayout常见属性以及方法的解析
c++·qt·面试·gui·客户端·布局管理器·水平布局器
小七在进步1 天前
string的实现(1)
c++·笔记·visual studio
kyle~1 天前
模型预测控制(MPC)
算法·机器人·控制·传感器
敲上瘾1 天前
Qt核心机制:信号与槽详解
开发语言·c++·qt·ui·qt6.3
牢姐与蒯1 天前
cpp算法之哈希
c++·算法·哈希算法
开开心心就好1 天前
两张表格数据对比工具,不用写函数也能查
算法·spring·智能手机·pdf·电脑·intellij-idea·音视频