216. 组合总和 III(中等,数组)(12.25)

找出所有相加之和为 n 的 个数的组合组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。

说明:

  • 所有数字都是正整数。
  • 解集不能包含重复的组合。 

示例 1:

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

示例 2:

输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]
class Solution:
    def combinationSum3(self, k, n):
        """
        :type k: int
        :type n: int
        :rtype: List[List[int]]
        """
        self.ans = []
        self.robot(0,[],k,n)
        return self.ans
    def robot(self,idx,tmp,k,n):
        if k == 0 and sum(tmp) == n:
            self.ans.append(tmp[:])
        for i in range(idx + 1,10):
            if i not in tmp:
                self.robot(i,tmp + [i],k-1,n)

执行用时: 52 ms, 在Combination Sum III的Python3提交中击败了49.37% 的用户

猜你喜欢

转载自blog.csdn.net/weixin_42234472/article/details/85246224