From 8a4b3b1636af1272e561db534f9a4ccbcec7e45f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9E=97=E7=BB=B5=E7=A8=8B?= Date: Fri, 17 Sep 2021 16:12:24 -0700 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00077.=E7=BB=84=E5=90=88python?= =?UTF-8?q?2=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0077.组合.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0077.组合.md b/problems/0077.组合.md index 9b44b572..c72adb83 100644 --- a/problems/0077.组合.md +++ b/problems/0077.组合.md @@ -368,6 +368,34 @@ class Solution { } ``` +Python2: +```python +class Solution(object): + def combine(self, n, k): + """ + :type n: int + :type k: int + :rtype: List[List[int]] + """ + result = [] + path = [] + def backtracking(n, k, startidx): + if len(path) == k: + result.append(path[:]) + return + + # 剪枝, 最后k - len(path)个节点直接构造结果,无需递归 + last_startidx = n - (k - len(path)) + 1 + result.append(path + [idx for idx in range(last_startidx, n + 1)]) + + for x in range(startidx, last_startidx): + path.append(x) + backtracking(n, k, x + 1) # 递归 + path.pop() # 回溯 + + backtracking(n, k, 1) + return result +``` Python: ```python3