> For the complete documentation index, see [llms.txt](https://cai-sen-se.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cai-sen-se.gitbook.io/leetcode/1-200/77.-zu-he.md).

# 77. 组合

<https://leetcode-cn.com/problems/combinations/>

## 解法一：dfs回溯

从1\~n中dfs遍历，每层递归取一位加入tmpList末尾，当tmp长度等于k时，**复制**到res中。

```python
class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        self.res = []
        tmpList = []
        self.dfs(n, k, tmpList, 1)    #从1开始dfs
        return self.res
    
    def dfs(self, n, k, tmpList, start):
        if len(tmpList) == k:
            self.res.append(list(tmpList))    #注意要用复制，而不是直接加入
        for i in range(start, n+1):
            self.dfs(n, k, tmpList + [i], i+1)    #start为i后一位
```
