1. 程式人生 > >【LeetCode 中等題】40-組合

【LeetCode 中等題】40-組合

題目描述:給定兩個整數 n 和 k,返回 1 ... 中所有可能的 k 個數的組合。

示例:

輸入: n = 4, k = 2
輸出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

解法1。使用庫函式itertools.combinations()

class Solution(object):
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        if n <= 0 or k > n:
            return []
        elif n == 1:
            return [[1]]
        import itertools
        res = []
        in_lst = [i+1 for i in range(n)]
        for lst in itertools.combinations(in_lst, k):
            if lst not in res:
                res.append(lst)
        return res

解法2。使用遞迴的方法。DFS深度優先搜尋的方法,從1開始append到sublist裡,如果sublist滿足長度就append到大集合res裡,返回到上一層記得pop出去,以及append的時候使用copy的方式sublist[:]而非直接appendsublist。

class Solution(object):
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        if n <= 0 or k > n:
            return
        elif n == 1:
            return [[1]]
        res = []
        sublist = []
        self.helper(n,k,1,sublist,res)
        return res
    
    def helper(self, n, k, start, sublist, res):
        if len(sublist) >= k:
            res.append(sublist[:])
            return
        for i in range(start, n+1):
            sublist.append(i)
            self.helper(n, k, i+1, sublist, res)
            sublist.pop()

參考連結:http://www.cnblogs.com/grandyang/p/4332522.html