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

[LeetCode] Combination Sum III

时间:2015-05-24 12:54:55      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

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]]

https://leetcode.com/problems/combination-sum-iii/

水题。另外该题还有一道扩展,如果只求给出方案的个数,不要求给出具体方案,而且数据量很大,那么就不能够用DFS了,这时候就得用动态规划来做,具体可以看我另一篇文章(k Sum):

http://www.cnblogs.com/easonliu/p/4508185.html

 1 class Solution {
 2 public:
 3     void dfs(int k, int n, int idx, int sum, int cnt, vector<int> &path, vector<vector<int> > &res) {
 4         if (sum > n || cnt > k || idx > 10) return;
 5         if (sum == n && cnt == k) {
 6             res.push_back(path);
 7             return;
 8         }
 9         dfs(k, n, idx + 1, sum, cnt, path, res);
10         path.push_back(idx);
11         dfs(k, n, idx + 1, sum + idx, cnt + 1, path, res);
12         path.pop_back();
13     }
14     
15     vector<vector<int>> combinationSum3(int k, int n) {
16         vector<vector<int>> res;
17         vector<int> path;
18         dfs(k, n, 1, 0, 0, path, res);
19         return res;
20     }
21 };

 

[LeetCode] Combination Sum III

标签:

原文地址:http://www.cnblogs.com/easonliu/p/4525607.html

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