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

LeetCode "Combination Sum III"

时间:2015-05-25 16:20:29      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

Typical recursion usage.

class Solution {
    vector<vector<int>> ret;
    void dfs(vector<int> curr, int currSum, int maxN, int n, int k)
    {
        //    Ending
        if (currSum == n)
        {
            if (curr.size() == k)
            {
                std::reverse(curr.begin(), curr.end());
                ret.push_back(curr);
            }
            return;
        }

        int rest = n - currSum;
        for (int c = maxN; c >= 1; c--)
        {
            if (c <= rest)
            {
                vector<int> ncurr = curr;
                ncurr.push_back(c);
                dfs(ncurr, currSum + c, c - 1, n, k);
            }
        }
    }
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        dfs(vector<int>(), 0, 9, n, k);
        return ret;
    }
}; 

LeetCode "Combination Sum III"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4527922.html

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