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]]
===================================================================
题目链接:https://leetcode.com/problems/combination-sum-iii/
题目大意:求出由1-9中某k个互不相同元素组成n的所有集合。
思路:深搜。
参考代码:
class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector < vector <int> > ans ;
vector <int> nums ;
if ( k == 0 && n == 0 )
{
ans.push_back ( nums ) ;
return ans ;
}
if ( k == 0 || n == 0 )
return ans ;
dfs ( k , ans , nums , n , 1 ) ;
return ans ;
}
void dfs ( int k , vector < vector <int> >& ans , vector <int>& nums , int n , int beg )
{
if ( k == 0 )
return ;
for ( int i = beg ; i <= 9 ; i ++ )
{
int dif = n - i ;
if ( dif > 0 )
{
nums.push_back ( i ) ;
dfs ( k - 1 , ans , nums , dif , i + 1 ) ;
nums.pop_back () ;
}
else if ( dif == 0 )
{
if ( k == 1 )
{
nums.push_back ( i ) ;
ans.push_back ( nums ) ;
nums.pop_back() ;
}
break ;
}
else
break ;
}
}
};