Leetcode 216. Combination Sum III

216. Combination Sum III

  • Total Accepted: 38824
  • Total Submissions: 102089
  • Difficulty: Medium

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

思路:回溯法,基本思路和类似,但要注意每个组合中不能有重复元素,例如k=3,n=7,那么[1,1,5]就不是答案。

代码:

 1 class Solution {
 2 public:
 3     vector<vector<int> > res;
 4     void combinationSum3(vector<int> v,int k,int n,int cur){
 5         if(!n&&!k){
 6             res.push_back(v);
 7             return;
 8         }
 9         if(k<=0){
10             return;
11         }
12         int i;
13         for(i=cur;i<10;i++){
14             n-=i;
15             if(n>=0){
16                 v.push_back(i);
17                 combinationSum3(v,k-1,n,i+1);
18                 v.pop_back();
19             }
20             else{
21                 return;
22             }
23             n+=i;
24         }
25     }
26     vector<vector<int> > combinationSum3(int k, int n) {
27         vector<int> v;
28         combinationSum3(v,k,n,1);
29         return res;
30     }
31 };
原文地址:https://www.cnblogs.com/Deribs4/p/5713688.html