硬币表示(循环递归)
问题描述如下:
用 1,5,10 三种面值的硬币表示 n,有多少种形式?
分析:
这个问题不同于其他的硬币问题,比如用最少的硬币表示 n 等,
而是要求可以构成面值 n 的硬币组合,使用递归就可以解决。
每个硬币都有取和不取两种状态,取得话又有取多个的情况,
因此可以使用循环中进行递归的方式来求解,即循环递归。
参考代码:
#include<iostream>
using namespace std;
int arr[3] = {1, 5, 10};
// 经典解法 循环递归
// left表示剩余待表示的总额
// arr为硬币的列表
// index为可以支配的硬币在列表中序号
int f(int left, int *arr, int index){
if(index == 0) return 1;
// temp表示当前要使用的硬币
int temp = arr[index];
int sum = 0;
// 表示取多少个当前的硬币 接下去递归
for(int i = 0; i*temp <= left; i++){
sum += f(left-i*temp, arr, index-1);
}
return sum;
}
int main(){
int n;
while(cin >> n){
cout << f(n, arr, 2) << endl;
}
return 0;
}
【END】感谢观看