ITPub博客

首页 > > > [LeetCode] Combination Sum III

[LeetCode] Combination Sum III

作者:Ruiyuan Li 时间:2015-05-25 00:00:00 0 删除 编辑

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

解题思路:

题意是,从1-9这9个数中,选出k个不同的数,使之和等于指定的值n。

理解题意后,题目就比较容易了。用一个递归模拟回溯即可。注意vector有个pop_back()的方法。这非常不错。

class Solution {
public:
    vector> combinationSum3(int k, int n) {
        vector> result;
        
        vector item;
        helper(result, item, 0, k, n);
        
        return result;
    }
    
    //max是item中最大的那个数,left是还剩下的值,k是需要找的数目
    void helper(vector>& result, vector& item, int max, int k, int left){
        if(item.size()==k&&left==0){
            result.push_back(item);
            return;
        }
        for(int i=max+1; i<=9&&i<=left; i++){
            item.push_back(i);
            helper(result, item, i, k, left-i);
            item.pop_back();
        }
    }
};


转载请注明: » [LeetCode] Combination Sum III
<!-- -->

原文作者:;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2020-05-21

  • 博文量
    495
  • 访问量
    4824