码迷,mamicode.com
首页 > 其他好文 > 详细

Combination Sum III -- leetcode

时间:2017-07-04 14:54:15      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:and   help   class   art   ott   etc   color   for   within   

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();
        }
    }
};


Combination Sum III -- leetcode

标签:and   help   class   art   ott   etc   color   for   within   

原文地址:http://www.cnblogs.com/gccbuaa/p/7116037.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!