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:
[[1,2,6], [1,3,5], [2,3,4]]
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
解题思路:
题意是,从1-9这9个数中,选出k个不同的数,使之和等于指定的值n。
理解题意后,题目就比较容易了。用一个递归模拟回溯即可。注意vector有个pop_back()的方法。这非常不错。
class Solution {
public:
vector> combinationSum3(int k, int n) {
vector> result;
vector item;
helper(result, item, 0, k, n);
return result;
}
//max是item中最大的那个数,left是还剩下的值,k是需要找的数目
void helper(vector>& result, vector& item, int max, int k, int left){
if(item.size()==k&&left==0){
result.push_back(item);
return;
}
for(int i=max+1; i<=9&&i<=left; i++){
item.push_back(i);
helper(result, item, i, k, left-i);
item.pop_back();
}
}
};
原文作者:;如有侵权,请联系管理员删除。