216. Combination Sum III Combination Sum III

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

Description:

  • All numbers are positive integers.
  • The solution set cannot contain repeated 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]]

combination

The full combination then filters out the results that meet the conditions.

Code

	def combinationSum3(self, k: int, n: int) -> List[List[int]]:
		ans, nums = [], [1, 2, 3, 4, 5, 6, 7, 8, 9]
		for item in itertools.combinations(nums, k):
			if sum(item) == n:
				ans.append(list(item))
		return ans

Guess you like

Origin blog.csdn.net/weixin_43336281/article/details/108527201