> For the complete documentation index, see [llms.txt](https://kerasnoone.gitbook.io/garnet/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kerasnoone.gitbook.io/garnet/suan-fa/hui-su/77-zu-he.md).

# \[77]\[中等]\[回溯] 组合

## 题目描述

[77. 组合](https://leetcode-cn.com/problems/combinations/)

给定两个整数 n 和 k，返回 1 ... n 中所有可能的 k 个数的组合。

示例:

```
输入: n = 4, k = 2
输出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]
```

## 解题思路

回溯方法, 注意去重, 限制下一层搜索的起点.

```python
class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        results = []

        def dfs(path, start):
            if len(path) == k:
                results.append(path[:])

            for i in range(start, n + 1):
                path.append(i)
                dfs(path, i + 1)
                path.pop()

        dfs([], 1)
        return results
```
