首页 > 代码库 > LeetCode77 Combinations

LeetCode77 Combinations

题目:

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. (Medium)

For example,
If n = 4 and k = 2, a solution is:

[  [2,4],  [3,4],  [2,3],  [1,2],  [1,3],  [1,4],]

分析:

求所有k长度的组合数。回溯的思路,每个元素可取可不取,到达k个元素则添加到结果中。

代码:

 1 class Solution { 2 private: 3     void helper(const vector<int>& seq, vector<int>& temp, int start, int k, vector<vector<int>>& result) { 4         if (k > seq.size() - start) { 5             return; 6         } 7         if (k == 0) { 8             result.push_back(temp); 9             return;10         }11         temp.push_back(seq[start]);12         helper(seq, temp, start + 1, k - 1, result);13         temp.pop_back();14         helper(seq, temp, start + 1, k, result);15         16     }17 public:18     vector<vector<int>> combine(int n, int k) {19         vector<int> seq(n);20         vector<vector<int>> result;21         for (int i = 0; i < n; ++i) {22             seq[i] = i + 1;23         }24         vector<int> temp;25         helper(seq,temp,0,k,result);26         return result;27     }28 };

 

LeetCode77 Combinations