Problem P09. [算法课动态规划] 换硬币
动态规划当前状态和之前状态息息相关。比如这题:组成硬币,已经组成好的硬币x加上面值为y的硬币就可以组成好x+y的硬币。所以要算出组成x+y的硬币,就要先算出组成x的硬币。可以用循环从x=0开始计算。
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int nums[] = {2, 5, 7};
int x[105]={0};
int main()
{
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++){
x[i]=-1;
}
int m = sizeof(nums)/4;
for (int i = 1; i <= n; i++){
for (int j = 0; j < m; j++){
if (i-nums[j]>=0&&x[i-nums[j]]!=-1){
int y = x[i-nums[j]]+1;
if (x[i]==-1||x[i]>y){
x[i]=y;
}
}
}
}
printf("%d", x[n]);
return 0;
}