Leecode 216. 组合总和 III C++ 回溯法

题目描述

找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。

说明:

所有数字都是正整数。
解集不能包含重复的组合。
示例 1:

输入: k = 3, n = 7
输出: [[1,2,4]]

示例 2:

输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]

解答

使用回溯法来做,这中方法用得很多,多次记录过。

class Solution {
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<vector<int>> res;
        vector<int> temp;
        fun(k, n, 1, temp, res);
        return res;
    }
    void fun(int k, int n, int index, vector<int> &temp, vector<vector<int>> &res)
    {
        if(0==n && temp.size()==k)
        {
            res.push_back(temp);
            return;
        }
        if(n<0 || temp.size()>k)
        {
            return;
        }
        while(index<=9)
        {
            temp.push_back(index);
            fun(k, n-index, index+1, temp, res);
            temp.pop_back();
            ++index;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/yuanliang861/article/details/89379502