看起来像一个经典的动态规划问题,其中的挑战是正确选择状态。
通常,我们选择选择硬币的总和作为问题状态,选择硬币的数量作为状态值。过渡是我们可以采取的每一种可能的硬币。如果我们有 25c 和 5c 硬币,我们可以从状态 Sum 与值 Count 移动到状态Sum+25,count+1
和Sum+5,count+1
。
为了您的限制,状态应该增加关于哪些特殊(顶级)硬币被拿走的信息。因此,您为每叠硬币添加一点。然后,您只需要定义每个状态的可能转换。这很简单:如果设置了堆栈位,则意味着顶部硬币已经被拿走,您可以从该堆栈中添加一个非顶部硬币到状态总和,保持所有位相同。否则,您可以从该堆栈中取出顶部的硬币,将其值添加到状态总和,并设置相关位。
您从总和为 0 的状态开始,所有位都清除且值为 0,然后从最低总和到目标构建状态。
最后,您应该遍历所有可能的位和组合。将状态值与目标总和以及该位组合进行比较。选择最小值 - 这就是答案。
示例解决方案代码:
#Available coins: (top coin value, other coins value)
stacks = [(17,8),(5,3),(11,1),(6,4)]
#Target sum
target_value = 70
states = dict()
states[(0,0)] = (0,None,None)
#DP going from sum 0 to target sum, bottom up:
for value in xrange(0, target_value):
#For each sum, consider every possible combination of bits
for bits in xrange(0, 2 ** len(stacks)):
#Can we get to this sum with this bits?
if (value,bits) in states:
count = states[(value,bits)][0]
#Let's take coin from each stack
for stack in xrange(0, len(stacks)):
stack_bit = (1 << stack)
if bits & stack_bit:
#Top coin already used, take second
cost = stacks[stack][1]
transition = (value + cost, bits)
else:
#Top coin not yet used
cost = stacks[stack][0]
transition = (value + cost, bits | stack_bit)
#If we can get a better solution for state with sum and bits
#update it
if (not (transition in states)) or states[transition][0] > count + 1:
#First element is coins number
#Second is 'backtrack reference'
#Third is coin value for this step
states[transition] = (count+1, (value,bits), cost)
min_count = target_value + 1
min_state = None
#Find the best solution over all states with sum=target_value
for bits in xrange(0, 2 ** len(stacks)):
if (target_value,bits) in states:
count = states[(target_value,bits)][0]
if count < min_count:
min_count = count
min_state = (target_value, bits)
collected_coins = []
state = min_state
if state == None:
print "No solution"
else:
#Follow backtrack references to get individual coins
while state <> (0,0):
collected_coins.append(states[state][2])
state = states[state][1]
print "Solution: %s" % list(reversed(collected_coins))