码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Combination Sum III

时间:2015-09-17 11:29:20      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

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.

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 };

 

[LeetCode]Combination Sum III

标签:

原文地址:http://www.cnblogs.com/Sean-le/p/4815579.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!