216. Combination Sum III

来源:互联网 发布:nba生涯得分数据 编辑:程序博客网 时间:2024/06/03 21:13

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]]
class Solution {public:    vector<vector<int>> ans;     void dfs(int k, int start, int sum, vector<int> v, int n){        if(v.size() == k){            if(sum == n)                ans.push_back(v);            return;        } else {            for(int i = start; i <= 9; ++i){                v.push_back(i);                dfs(k, i + 1, sum + i, v, n);                v.pop_back();            }        }    }    vector<vector<int>> combinationSum3(int k, int n) {        vector<int> v;        dfs(k, 1, 0, v, n);        return ans;    }};
0 0