Combination Sum III -- leetcode

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]]

Credits:


基本思路:

使用dfs进行穷举遍历。

因为结果集要求按升序排列,则先选择较小的数字,然后从剩下的较大数中进行选择。

确保每次选择的数都大于上次选择的。


class Solution {
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<vector<int>> ans;
        vector<int> seq;
        helper(ans, seq, k, n);
        return ans;
    }
    
    void helper(vector<vector<int>>& ans, vector<int>& seq, int k, int n) {
        if (!k && !n)
            return ans.push_back(seq);
        
        if (!k || n<0)
            return;
        
        int start = seq.empty() ? 1 : seq.back()+1;
        for (int i=start; i<=9; i++) {
            seq.push_back(i);
            helper(ans, seq, k-1, n-i);
            seq.pop_back();
        }
    }
};


posted @ 2017-07-04 12:35  gccbuaa  阅读(138)  评论(0编辑  收藏  举报