题目描述
题目链接: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
,因此同样用回溯法求解即可,代码如下:
1 |
|
- 时间复杂度: O(2^n)
- 空间复杂度: O(Cnk)
GitHub 代码同步地址: 77.Combinations.cpp
其他题目:
GitHub: Leetcode-C++-Solution
博客: Leetcode-Solutions