[leetcode] 216. Combination Sum III @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/86604314

原题

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Note:

All numbers will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:

Input: k = 3, n = 7
Output: [[1,2,4]]
Example 2:

Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]

解法1

使用itertools.combinations()方法, 直接求排列组合的结果, 然后从结果中找出元组的和为n的元组, 将元组转化为列表.
Time: O(n)
Space: O(1)

代码

class Solution:
    def combinationSum3(self, k, n):
        """
        :type k: int
        :type n: int
        :rtype: List[List[int]]
        """
        nums = range(1, 10)
        com = itertools.combinations(nums, k)
        res = [list(tup) for tup in com if sum(tup) == n]
        return res

解法2

DFS + backtracking. 在DFS函数里, 回溯的条件是当k<0或者n<0, 此时直接返回. 当k=0 并且n=0时, 表明我们找到了k个数字的组合,使得它们的和为n, 将path加到res里. 然后对nums进行遍历和递归.

代码

class Solution:
    def combinationSum3(self, k, n):
        """
        :type k: int
        :type n: int
        :rtype: List[List[int]]
        """
        res = []
        nums = range(1, 10)
        self.dfs(nums, k, n, 0, [], res)
        return res
        
    def dfs(self, nums, k, n, index, path, res):
        # edge case
        if k < 0 or n < 0:
            return
        # when reaching the end
        if k == 0 and n == 0:
            res.append(path)
        for i in range(index, len(nums)):
            self.dfs(nums, k-1, n-nums[i], i+1, path+[nums[i]], res)

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/86604314