LeetCode77 Combinations

Posted wangxiaobao的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

[Lintcode]152. Combinations/[Leetcode]77. Combinations

leetcode-Combinations-77

leetcode 77. Combinations 组合(中等)

#Leetcode# 77. Combinations

Leetcode 77, Combinations

<LeetCode OJ> 77. Combinations