题目描述:

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

解题思路:

本题因为数组的元素个数的个数没有限制,所以循环的就不便于实现,我用了递归的方法遍历添加1-9,直到元素的个数为k-1,比较最后一个数(n-数组中所有数)是否小于10且大于数组中的最后一个数。

代码:

 1 class Solution {
 2 public:
 3     void select(vector<vector<int>> &ret, vector<int> nums, int k, int n, int index, int count){
 4         nums.push_back(index+1);
 5         int len = nums.size();
 6         if(count == k-1){
 7         //这里我默认k的数值至少为2
 8             for(int i = 0; i < len; i++){
 9                 n -= nums[i];
10             }
11             if(n < 10 && nums[len-1] < n){
12                 nums.push_back(n);
13                 ret.push_back(nums);
14             }
15         }
16         for(int i = index+1; i < 9 && i < n; i++){
17         //遍历向下添加
18             select(ret, nums, k, n, i, count+1);
19         }
20     }
21     vector<vector<int>> combinationSum3(int k, int n) {
22         vector<vector<int>> ret;
23         for(int i = 0; i < 8; i++)
24             select(ret, vector<int>() , k, n, i, 1);
25         return ret;
26     }
27 };

 

posted on 2018-04-08 23:42  宵夜在哪  阅读(106)  评论(0编辑  收藏  举报