[LeetCode-Algorithms-216] "Combination Sum III" (2018.1.1-WEEK18)

题目链接: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.

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

(1)思路:递归循环调用。用一个向量num存现有的数字集合,如果n<0,则直接返回;如果n=0,且此num中数字的个数正好为k,则是正确解,将其存入结果result中。

(2)代码:

class Solution {
public:
    vector<vector<int> > combinationSum3(int k, int n) {
        vector<vector<int> > result;
        vector<int> num;
        muladd(k, n, 1, num, result);
        return result;
    }
    void muladd(int k, int n, int level, vector<int> &num, vector<vector<int> > &result){
        if(n < 0) return;
        if(n == 0 && num.size() == k) result.push_back(num);
        for(int i=level; i<=9; ++i){
            num.push_back(i);
            muladd(k, n-i, i+1, num, result);
            num.pop_back();
        }
    }
};

(3)提交结果:

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_33454112/article/details/78947785