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]]
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
解题思路:
深搜?因为在9之内所以时间应该不会很高。
- class Solution {
- private:
- vector<vector<int>> ret;
- vector<int> store;
- void deep(int &k,int &n,int cur_num,int count,int sum){
- count++;
- sum+=cur_num;
- store.push_back(cur_num);
- if(count == k){
- if(n==sum) {ret.push_back(store);return;}
- }
- else{
- for(int j=cur_num+1;j<=9;j++){
- deep(k,n,j,count,sum);
- store.pop_back();
- }
- }
- }
- public:
- vector<vector<int>> combinationSum3(int k, int n) {
- for(int i=1;i<=9;i++){
- if((9-i+1)>=k)
- deep(k,n,i,0,0);
- store.clear();
- }
- return ret;
- }
- };