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.
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:
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]]
思路:给定一个数k和一个数n。求k个1-9的数字相加之和等于给定的数字n。
class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<int>slo;
vector<vector<int>>res;
vector<int>nums(9);
if(k<=0||n<=0||9*k<n)
return res;
for(int i=0;i<nums.size();i++)
nums[i]=i+1;
DFS(nums,0,slo,res,n,k);
return res;
}
void DFS(vector<int>&nums,int index,vector<int>&slo,vector<vector<int>>&res,int n,int k)
{
if(n==0&&slo.size()==k)
{
res.push_back(slo);
return;
}
for(int i=index;i<nums.size();i++)
{
if(nums[i]<=n&&slo.size()<=k)
{
slo.push_back(nums[i]);
DFS(nums,++index,slo,res,n-nums[i],k);
slo.pop_back();
}
}
}
};