216. Combination Sum III

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之内所以时间应该不会很高。

 

  1. class Solution {  
  2.     private:  
  3.               
  4.      vector<vector<int>> ret;  
  5.     vector<int> store;  
  6.   
  7.     void deep(int &k,int &n,int cur_num,int count,int sum){  
  8.         count++;  
  9.         sum+=cur_num;  
  10.         store.push_back(cur_num);  
  11.         if(count == k){  
  12.             if(n==sum) {ret.push_back(store);return;}  
  13.         }  
  14.         else{  
  15.             for(int j=cur_num+1;j<=9;j++){  
  16.                 deep(k,n,j,count,sum);  
  17.                 store.pop_back();  
  18.             }  
  19.         }  
  20.     }  
  21. public:  
  22.     vector<vector<int>> combinationSum3(int k, int n) {  
  23.           
  24.   
  25.         for(int i=1;i<=9;i++){  
  26.             if((9-i+1)>=k)  
  27.             deep(k,n,i,0,0);  
  28.             store.clear();  
  29.   
  30.         }  
  31.         return ret;  
  32.     }  
  33. };  
posted @ 2018-04-13 14:16  一日一更  阅读(58)  评论(0编辑  收藏  举报