LeetCode 之 Combination Sum III

来源:互联网 发布:辐射4xboxonex优化 编辑:程序博客网 时间:2024/05/16 17:36

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.

Ensure that numbers within the set are sorted in ascending order.


Example 1:

Input: k = 3, n = 7

Output:

[[1,2,4]]


Example 2:

Input: k = 3, n = 9

Output:

[[1,2,6], [1,3,5], [2,3,4]]

这道题和之前的全排列问题有点类似,先在1到9中选择一个元素i,把问题转化为(k-1,n-i)问题,这样递归解决,关键是我们要存储中间结果方便回溯,每次到达底部后(n==0和k==0)返回。代码如下:

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



0 0