Longest Common Prefix (Python)
Maximum Subarray (Python)

Combinations (Python)

kitt posted @ 2014年1月31日 21:05 in LeetCode , 2224 阅读

递归解法和非递归解法都能过。非递归解法中p指针指的位置如果达到了允许的最大值, p指针就前移。比如C(5,3)得到了[1,2,5], p指向第三个位置已经达到了最大值5, 则p前移,指向第二个位置,c[p]+=1, 于是得到[1,3,4]。当p指向第一个位置且它达到最大值,也就是[3,4,5]的时候就结束了,多谢朱老师的点播。递归解法要注意C(self, List, k)返回的是list of list。

 

class Solution:
    # @return a list of lists of integers
    def combine(self, n, k):
        res = []
        if k == 0:
            return res
        c = [0 for i in xrange(k)]
        p = 0
        # p is a position, if c[p] reaches max, --p
        while p >= 0:
            c[p] += 1
            for i in xrange(p+1, k):
                c[i] = c[i-1] + 1
            res.append(list(c))
            p = k-1
            while p >= 0 and c[p] == n - (k - 1 - p):
                p -= 1
        return res
class Solution:
    # @return a list of lists of integers
    def combine(self, n, k):
        return self.C(range(1,n+1), k)
        
    def C(self, List, k):
        res = []
        length = len(List)
        if k <= 0 or length < k:
            return res
        for i in xrange(length):
            if k == 1:
                res.append( list((List[i],)) )
            else:
                for item in self.C(List[i+1:], k-1):
                    res.append( [List[i]] + item )
        return res

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter