lintcode_152.组合

组给出两个整数n和k,返回从1......n中选出的k个数的组合。

样例

例如 n = 4 且 k = 2

返回的解为:

[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4]]

 

递归回溯思想,用k控制内循环次数,从而控制每一个元素中数的个数

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  
        self.res = []
        tmp = []
        self.dsf(n,k,1,0,tmp)
        
        return self.res
        
    def dsf(self, n, k, m, p, tmp):
        if k == p: #当p == k:说明tmp中元素个数为k,可以添加到结果中
            self.res.append(tmp[:])
            return
        for i in range(m, n+1):
            tmp.append(i)
            self.dsf(n, k, i+1, p+1, tmp) #p也代表了递归次数
            tmp.pop() #将最后一位剔除,更新新的元素

 

 

posted @ 2018-01-05 11:11  Tom_NCU  阅读(98)  评论(0编辑  收藏  举报