216. 組合總和 III(中等,陣列)(12.25)
阿新 • • 發佈:2019-01-05
找出所有相加之和為 n 的 k 個數的組合。組合中只允許含有 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% 的使用者