简繁EN

LeetCodeNo. 115

【LeetCode with Python】 39. Combination Sum

目錄

題目

原題頁面:https://leetcode.com/problems/combination-sum/
題目型別:Array, Backtracking
難度評價:Medium
類似題目:(M) Letter Combinations of a Phone Number, (M) Combination Sum II, (M) Combinations, (M) Combination Sum III, (M) Factor Combinations

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

The same repeated number may be chosen from C unlimited number of times.

Note:

  1. All numbers (including target) will be positive integers.
  2. Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  3. The solution set must not contain duplicate combinations.

For example, given candidate set 2,3,6,7 and target 7,

A solution set is:
[7]
[2, 2, 3]


分析

比較經典的遞歸回溯和組合問題。每個元素可以被使用多次,注意引數傳入的set可能不是有序的,為確保萬一先sort吧(有可能不需要?因為set中沒有重複元素,不會產生重複解)。這道題有兩個值得思考的地方:
為什麼不能用動態規劃來解決這個問題?什麼樣的題可以用動態規劃,動態規劃究竟是什麼,這個定義上的問題一直困擾著本人。但是至少可以確定一點,動態規劃是用來解決最最佳化問題的,而不是組合問題。例如如果這道題改為,從集合中挑選出一個子集合,使其最接近於給出的target值,但是又不能超過target值,那這道題就是動態規劃中典型的背包問題了。(好像不太對,像Interleaving String這個DP問題就是一個排列問題,而不是一個最佳化問題。DP問題可能得是一個可迭代分解的問題。)
無限遞迴問題。注意程式碼中的used變數,因為set中的值可以被使用多次。。。
另外注意題目說的是“a set of candidate numbers”,既然是set,說明numbers中是沒有重複元素的。
(本題感覺理解得還不是很清楚)


程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution:

def __init__(self):
self.nums = None
self.len_nums = 0
self.total = 0
self.combinations = [ ]

def doCombinationSum(self, prefix, prefix_total, start, last, used):
if start >= self.len_nums:
return
num = self.nums[start]

result = True
# 只有当第一次考察该元素,或虽然不是第一次考察该元素,但是该元素上一轮已经被采用,才能继续下去
if num != last or used: ###
if prefix_total + num == self.total:
new_prefix = prefix[:]
new_prefix.append(num)
self.combinations.append(new_prefix)
return
elif prefix_total + num < self.total:
new_prefix = prefix[:]
new_prefix.append(num)
self.doCombinationSum(new_prefix, prefix_total + num, start + 1, num, True)
self.doCombinationSum(new_prefix, prefix_total + num, start, num, True)
else:
return
# 决定不采用该元素并且将索引+1,只能发生在第一次考察该元素的时候,否则会有重复组合加入
if num != last: ###
self.doCombinationSum(prefix, prefix_total, start + 1, num, False)
return True

# @param candidates, a list of integers
# @param target, integer
# @return a list of lists of integers
def combinationSum(self, candidates, target):
self.combinations = [ ]
self.nums = candidates
self.nums.sort()
self.len_nums = len(self.nums)
if 0 == self.len_nums:
return [ ]
self.total = target
self.doCombinationSum([ ], 0, 0, -1, True)
return self.combinations

本文地址:https://xnerv.wang/zh-tw/leetcode-combination-sum/