LintCode:组合

来源:互联网 发布:cmd关闭端口命令 编辑:程序博客网 时间:2024/06/05 14:44

LintCode:组合

回溯算法,注意python的话要用到一个深拷贝。

import copyclass 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])
0 0