回溯算法,注意python的话要用到一个深拷贝。
import copy
class Solution:
"""
@param n: Given the range of numbers
@param k: Given the numbers of combinations
@return: All the combinations of k numbers out of 1..n
"""
def combine(self, n, k):
# write your code here
if n < k:
return 0
self.res = []
cur = []
self.my_combine(cur, 1, n, k, self.res)
return self.res
def my_combine(self, cur, index, n, k, res):
if len(cur) == k:
res.append(copy.copy(cur))
return
for index in range(index, n+1):
cur.append(index)
self.my_combine(cur, index + 1, n, k, res)
cur.remove(cur[len(cur)-1])