跳到主要内容

Combination Sum II

描述

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1,a2,...,aka_1, a_2, ..., a_k) must be in non-descending order. (ie, a1>a2>...>aka_1 > a_2 > ... > a_k).
  • The solution set must not contain duplicate combinations.

For example, given candidate set 10,1,2,7,6,1,5 and target 8, A solution set is:

[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]

分析

代码

# Combination Sum II
# time complexity O(n!), space complexity O(n)
class Solution:
def combinationSum2(self, nums: list[int], target: int) -> list[list[int]]:
nums.sort() # works with line 32,
# ensures each element is used at most once
result = []
path = []
self.dfs(nums, path, result, target, 0)
return result

# Use elements between nums[start, nums.size()) to find all possible solutions
def dfs(self, nums: list[int], path: list[int], result: list[list[int]], gap: int, start: int) -> None:
if gap == 0: # found a valid solution
result.append(path[:])
return

previous = -1
for i in range(start, len(nums)):
# if nums[i] was used in the previous round, we can't use nums[i] in this round,
# ensures nums[i] is used at most once
if previous == nums[i]:
continue

if gap < nums[i]:
return # pruning

previous = nums[i]

path.append(nums[i])
self.dfs(nums, path, result, gap - nums[i], i + 1)
path.pop() # restore environment

相关题目