77. Combinations

depth first search, recursive function 
class Solution(object):
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        result=[]
        self.combineRecur(n,result,0,[],k)
        return result
    def combineRecur(self,n,result,start,out,k):
        if k==0:
            result.append(out[:])
            return 
        for i in xrange(start,n):
            out.append(i+1)
            self.combineRecur(n,result,i+1,out,k-1)
            out.pop()
            if (k-len(out))>n-i:
                return
from itertools import combinations
class Solution(object):
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        return list(combinations(range(1,n+1),k))
using list comprehension 

class Solution(object):
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        if k == 0:
            return [[]]
        return [[i]+rest for i in range(1,n+1) for rest in self.combine(i-1,k-1)]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容