算法趣题-Q05
作者:互联网
一、问题描述
二、问题分析
经过Q04的题目后,这道题也同样可以视为是将一个大问题拆分成同类型小问题。于是,依旧选择递归算法。
三、代码实现
1.C/C++实现
#include <iostream>
using namespace std;
int coins[5] = { 500, 100, 50, 10, 0 };
int change(int money, int max_count, int type)
{
// 将 money 找零,最多为 max_count 个零钱,零钱面值为 coins[type]
if (max_count * coins[type] < money || money < 0)
{
return 0;
}
else if (money == 0)
{
return 1;
}
else
{
int count = 0;
for (int i = 0; i <= max_count && i <= money / coins[type]; i++)
{
count += change(money - i * coins[type], max_count - i, type + 1);
}
return count;
}
}
int main()
{
cout << change(1000, 15, 0) << endl;
return 0;
}
2.Python实现
# coding=utf-8
def change(money, max_count, coins):
# 这里的 coins 与 C/C++ 算法不同,传递的是 coins 面值列表
if money == 0:
return 1
elif len(coins) == 0 or (max_count * coins[0] < money):
return 0
else:
i = 0
count = 0
while i <= max_count and i <= money / coins[0]:
count += change(money - i * coins[0], max_count - i, coins[1:])
i += 1
return count
if __name__ == '__main__':
print(change(1000, 15, [500, 100, 50, 10]))
标签:count,return,int,money,coins,算法,趣题,max,Q05 来源: https://blog.csdn.net/qq_41893962/article/details/120195588