115、【回溯算法】leetcode ——216.组合总和III:回溯法+剪枝优化(C++/Python版本)

题目描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
原题链接:216.组合总和III

解题思路

整体回溯法思路类似于 77. 组合(回溯法+剪枝优化),与之不同的是,需要多一个相加和为n的判定条件,可以让每次传入数的时候进行n - i,直至找到n == 0时,再将结果压入结果集中。

一、回溯法

class Solution {
public:
    vector<vector<int>> res;
    void backtracking(int k, int n, int startIndex, vector<int> path) {    
        if(path.size() == k) {                        
            if(n == 0) {
                res.push_back(path);                      
            }
            return ;
        }
        for(int i = startIndex; i <= 9; i++) {
            path.push_back(i);
            backtracking(k, n - i, i + 1, path);
            path.pop_back();
        }
    }
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<int> path;
        backtracking(k, n, 1, path);
        return res;
    }
};

Python

class Solution:
    def __init__(self):
        self.res = []
        self.path = []

    def backtracking(self, k, n, startIndex):
        if n < 0:
            return 
        elif len(self.path) == k and n == 0:     
            self.res.append(self.path[:])
            return
        
        for i in range(startIndex, 10):
            self.path.append(i)
            self.backtracking(k, n - i, i + 1)
            self.path.pop()            


    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        self.backtracking(k, n, 1)
        return self.res



二、剪枝优化

可利用从小到大的顺序遍历startIndex控制遍历下界n - (k - path.size())控制遍历上界,从而实现剪枝的过程。
其中,path.size():表示当前已存入的数,k - path.size():表示当前还可以再存几个数,n - (k - path.size()) + 1:表示当前最大的遍历起始位置。

class Solution {
public:
    vector<vector<int>> res;
    void backtracking(int k, int n, int startIndex, vector<int> path) {    
        if(path.size() == k) {                        
            if(n == 0) {
                res.push_back(path);                      
            }
            return ;
        }
        // 当startIndex控制遍历下界,9 - (k - path.size()) + 1控制遍历上界
        for(int i = startIndex; i <= 9 - (k - path.size()) + 1; i++) {
            path.push_back(i);
            // n - i < 0说明当前以及后面的数都不会满足要求,直接返回即可
            if(n - i < 0)      return ;
            backtracking(k, n - i, i + 1, path);
            path.pop_back();
        }
    }
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<int> path;
        backtracking(k, n, 1, path);
        return res;
    }
};

Python

class Solution:
    def __init__(self):
        self.res = []
        self.path = []

    def backtracking(self, k, n, startIndex):
        if n < 0:
            return 
        elif len(self.path) == k and n == 0:     
            self.res.append(self.path[:])
            return
        
        for i in range(startIndex, 10 - (k - len(self.path)) + 1):
            self.path.append(i)
            self.backtracking(k, n - i, i + 1)
            self.path.pop()            


    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        self.backtracking(k, n, 1)
        return self.res



参考文章:114、【树与二叉树】leetcode ——77. 组合:回溯法+剪枝优化(C++版本)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

辰阳星宇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值