40.組み合わせ和II組み合わせ和II

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates の各番号は、各組み合わせで1回だけ使用できます。

説明:

  • すべての数値(ターゲット数を含む)は正の整数です。
  • ソリューションセットに繰り返しの組み合わせを含めることはできません。 

例1:

入力: candidates = [10,1,2,7,6,1,5], target = 8
ソリューションセットは次のとおりです。
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

例2:

入力: candidates = [2,5,2,1,2], target = 5
ソリューションセットは次のとおりです。
[
  [1,2,2],
  [5]
]

再帰

昨日の39. Combination Sumと同じですが、各数値を制限する条件は一度しか使用できません。

コード

	def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
		def dfs(start, use, remain):
			for index, value in enumerate(candidates[start:]):
				if value == remain and use + [value] not in ans:
					ans.append(use + [value])
				elif value < remain:
					dfs(start + index + 1, use + [value], remain - value)
				else:
					return 

		ans = []
		candidates.sort()
		dfs(0, [], target)
		return ans

おすすめ

転載: blog.csdn.net/weixin_43336281/article/details/108506463