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

Leetcode题解(4):L216/Combination Sum III

时间:2015-06-08 15:03:38      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:递归   algorithms   leetcode   

L216: Combination Sum III
  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]]

解题思路:递归,注意一些条件的处理,避免不必要的处理

class Solution {
public:
bool combine(int min, int k, int n, vector<int> vec, vector<vector<int>>& result){
        if(n<min*k)         //更确切的,可以用等差数列公式算出最大值最小值
            return false;
        if(n>9*k)
            return true;

        if(k==1)
        {
            vec.push_back(n);
            result.push_back(vec);
            return true;
        }

        for(int i=min;i<=9;i++)
        {
            vec.push_back(i);
            bool rt = combine(i+1, k-1,n-i, vec, result);
            vec.pop_back();
            if(!rt)
                break;
        }
        return true;
    }

    vector<vector<int>> combinationSum3(int k, int n) {
        vector<vector<int>> result;
        vector<int> vec;
        combine(1,k,n,vec,result);
        return result;
    }
};

Leetcode题解(4):L216/Combination Sum III

标签:递归   algorithms   leetcode   

原文地址:http://blog.csdn.net/kzq_qmi/article/details/46412289

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