题目描述
题目链接:77. Combinations
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
解题思路
这道题可以理解成 [Leetcode]78. Subsets(C++) 的一种形式,这里的输入数组为 1 ~ n
,并且要求子集的长度的是 k
,因此同样用回溯法求解即可,代码如下:
#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
其他题目: GitHub: Leetcode-C++-Solution 博客: Leetcode-Solutions