【leetcode】216. Combination Sum III

题目:
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.


思路:
直观思路,递归尝试所有可能组合。


代码实现:

class Solution {
public:
    void f(vector<bool> &isSelected, int begin, int remain, int sum, vector<vector<int>> &ans, vector<int> &tmp){
        if (sum < 0){
            return ;
        }
        if (remain == 0 && sum == 0){
            ans.push_back(tmp);
            return ;
        }
        
        for (int i = begin; i < isSelected.size(); ++i){
            if (isSelected[i] == false){
                isSelected[i] = true;
                tmp.push_back(i);
                f(isSelected, i, remain-1, sum-i, ans, tmp);
                tmp.pop_back();
                isSelected[i] = false;
            }
        }
        
    }
    
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<bool> isSelected(10, false);
        vector<vector<int>> ans;
        vector<int> tmp;
        
        f(isSelected, 1, k, n, ans, tmp);
        
        return ans;
    }
};

在这里插入图片描述


原创文章 299 获赞 2 访问量 1万+

猜你喜欢

转载自blog.csdn.net/zxc120389574/article/details/106066890