[Leetcode]Combination Sum III

来源:互联网 发布:天津mac彩妆专柜 编辑:程序博客网 时间:2024/05/11 22:08

Find all possible combinations of k numbers that add up to a numbern, 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.

class Solution {public:    void dfs(vector<vector<int>>&result,vector<int>&path,int start,int k,int n){        if(n < 0 || path.size() > k)return;        if(path.size() == k){            if(n == 0)result.push_back(path);            return;        }        for(int i = start;i < 10;i++){            path.push_back(i);            dfs(result,path,i+1,k,n-i);            path.pop_back();        }    }    vector<vector<int>> combinationSum3(int k, int n) {            vector<vector<int>>result;            vector<int>path;            dfs(result,path,1,k,n);            return result;    }};

0 0