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

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

 

posted @ 2015-05-24 11:54  Eason Liu  阅读(999)  评论(1编辑  收藏  举报