Combinations

很传统的回溯题了,需要注意的是这里的出口有两个标准要进行判断

class Solution(object):
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        if k > n:
            return []

        tmp, res = [], []
        self.helper(1, n + 1, 0, k, tmp, res)
        return res

    def helper(self, start, end, count, limit, tmp, res):
        if count == limit:
            ref = tmp[:]
            res.append(ref)
            return 

        if start >= end:
            return

        for i in xrange(start, end):
            tmp.append(i)
            self.helper(i + 1, end, count + 1, limit, tmp, res)
            tmp.pop()

results matching ""

    No results matching ""