leetcode---Combination Sum III---回溯

来源:互联网 发布:伤感歌曲网络歌曲 编辑:程序博客网 时间:2024/04/30 11:49

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;    vector<int> tmp;        void dfs(int k, int n, int dep, int sum, vector<int> &tmp)    {        if(dep > k)        {            if(sum == n && tmp.size() == k)                ans.push_back(tmp);        }        for(int i=dep; i<=9; i++)        {            if(sum + i <= n)            {                tmp.push_back(i);                dfs(k, n, i+1, sum+i, tmp);                tmp.pop_back();            }        }    }    vector<vector<int>> combinationSum3(int k, int n)     {        dfs(k, n, 1, 0, tmp);        return ans;    }};


 

0 0
原创粉丝点击