标签:
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.
继续dfs,不用判断重复。
1 class Solution { 2 public: 3 void dfs(int k,int n,int val,vector<int> tmp,vector<vector<int>>& result) 4 { 5 if(tmp.size()==k) 6 { 7 int sum=0; 8 for(int i=0;i<tmp.size();i++) 9 { 10 sum+=tmp[i]; 11 } 12 if(sum==n) result.push_back(tmp); 13 return; 14 } 15 for(int i=val;i<=9;i++) 16 { 17 tmp.push_back(i); 18 dfs(k,n,i+1,tmp,result); 19 tmp.pop_back(); 20 } 21 } 22 vector<vector<int>> combinationSum3(int k, int n) { 23 vector<int> tmp; 24 vector<vector<int>> result; 25 dfs(k,n,1,tmp,result); 26 return result; 27 } 28 };
标签:
原文地址:http://www.cnblogs.com/Sean-le/p/4815579.html