随笔 - 109, 文章 - 0, 评论 - 3, 阅读 - 51232

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

【力扣】求组合(回溯算法)

Posted on   SaTsuki26681534  阅读(8)  评论(0编辑  收藏  举报

题目描述

image
2.
image
以下是回溯算法的模版

class Solution {
private:
    vector<vector<int>> res;
    vector<int> path;//这个变量名还是设为path更合适
    void backtrace(int n, int k, int startindex){
        //递归结束条件,这个是根据问题要求修改的
        if(path.size() == k){
            //找到了一个合适的组合
            res.push_back(path);
            return ;
        }

        //回溯过程
        for(int i = startindex; i <= n - (k - path.size()) + 1; i++){
            path.push_back(i);
            //向下递归的操作可以看作一个子问题
            backtrace(n,k,i+1);
            path.pop_back();
        }
    }
public:
        vector<vector<int>> combine(int n, int k) {
        res.clear();
        path.clear();
        backtrace(n,k,1);
        return res;
    }
};
class Solution {
public:
    vector<vector<int>> res;
    vector<int> path;
    void backtrace(int n, int k, int startindex){
        if(path.size() == k && accumulate(path.begin(), path.end(), 0) == n){
            res.push_back(path);
            return ;
        }

        for(int i = startindex; i <= 9; i++){
            path.push_back(i);
            backtrace(n,k,i+1);
            path.pop_back();
        }
    }
    vector<vector<int>> combinationSum3(int k, int n) {
        res.clear();
        path.clear();
        backtrace(n, k, 1);
        return res;
    }
};
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示