## [Leetcode]77. Combinations(C++)

### 题目描述

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

You may return the answer in any order.

### 例子

#### 例子 1

Input: `n = 4, k = 2` Output: `[` ` [2,4],` ` [3,4],` ` [2,3],` ` [1,2],` ` [1,3],` ` [1,4],` `]`

#### 例子 2

Input: `n = 1, k = 1` Output: `[[1]]`

### Constraints

• `1 <= n <= 20`
• `1 <= k <= n`

### 解题思路

``````#include <vector>

class Solution {
public:
std::vector<std::vector<int>> combine(int n, int k) {
std::vector<int> comb;
std::vector<std::vector<int>> result;
dfs(1, n, k, comb, result);
return result;
}

private:
void dfs(int idx, int n, int k, std::vector<int> comb,
std::vector<std::vector<int>>& result) {
if (comb.size() == k) {
result.push_back(comb);
return;
}
for (int i = idx; i <= n; ++i) {
comb.push_back(i);
dfs(i + 1, n, k, comb, result);
comb.pop_back();
}
}
};
``````
• 时间复杂度: O(2^n)
• 空间复杂度: O(Cnk)

GitHub 代码同步地址： 77.Combinations.cpp

Built with Hugo
Theme Stack designed by Jimmy