其他分享
首页 > 其他分享> > 递归和回溯_leetcode77

递归和回溯_leetcode77

作者:互联网

class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
self.res = []

if not n or k > n or k <= 0:
return self.res

self.generateCombinations(n,k,1,[])

return self.res


# 求解C(n,k) ,当前已经找到的组合存储在c中,需要从start开始搜索新的元素
def generateCombinations(self,n,k,start,ans):

if len(ans) == k:
self.res.append(ans[0:])
return

for i in range(start,n+1):

ans.append(i)
self.generateCombinations(n,k,i+1,ans)
ans.pop()



# 剪支,就是减少 for 循环的上限

class Solution2(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
self.res = []

if not n or k > n or k <= 0:
return self.res

self.generateCombinations(n,k,1,[])

return self.res


# 求解C(n,k) ,当前已经找到的组合存储在ans中,需要从start开始搜索新的元素
def generateCombinations(self,n,k,start,ans):

if len(ans) == k:
self.res.append(ans[0:])
return

# 还有k-len(ans)个空位,[i,…,n]中至少还有 k-len(ans)个元素
# i最多为 n -(k-len(ans)) + 1

for i in range(start,n-(k-len(ans))+2):

ans.append(i)
self.generateCombinations(n,k,i+1,ans)
ans.pop()

标签:generateCombinations,leetcode77,递归,int,res,self,回溯,start,ans
来源: https://www.cnblogs.com/lux-ace/p/10556973.html