题意:给若干硬币和要支付的价钱,返回最小的支付的结果,若没有支付方案则输出No Solution。
题干不难理解,此题可以用dfs通过。
其中测试点6是大规模数据,并且答案还是No Solution,所以先对所有硬币求和小于M直接输出。
非零返回问题:
错误代码:
N, M = map(int, input().split())
coins = sorted(list(map(int, input().split())))
def dfs(i, total):
if total == M:
print(' '.join(list(map(str, ans))))
return True
if i >= N or total > M :
return False
ans.append(coins[i])
if dfs(i + 1, total + coins[i]):
return True
ans.pop(-1)
if dfs(i + 1, total):
return True
return False
ans = []
if sum(coins)<M or not dfs(0, 0) :
print('No Solution')
测试点34出现非零返回的问题,发现其其实代码本身没有问题,可能是因为数据规模太大程序崩溃了。
对dfs进行剪枝:
1.当前和已经大于目标
2.当前硬币价值大于目标
3.当前硬币价值大于满足目标所需的硬币价值
if i >= N or total > M or coins[i] > M or M - total < coins[i]:
return False
23两点恰好对应了测试点34的问题。
完整代码
N, M = map(int, input().split())
coins = sorted(list(map(int, input().split())))
def dfs(i, total):
if total == M:
print(' '.join(list(map(str, ans))))
return True
if i >= N or total > M or coins[i] > M or M - total < coins[i]:
return False
ans.append(coins[i])
if dfs(i + 1, total + coins[i]):
return True
ans.pop(-1)
if dfs(i + 1, total):
return True
return False
ans = []
if sum(coins)<M or not dfs(0, 0) :
print('No Solution')