题目描述
给定数组arr,arr中所有的值都为正整数且不重复。每个值代表一种面值的货币,每种面值的货币可以使用任意张,再给定一个aim,代表要找的钱数,求组成aim的最少货币数。
输入描述:
输入包括两行,第一行两个整数n(0<=n<=1000)代表数组长度和aim(0<=aim<=5000),第二行n个不重复的正整数,代表arr(1≤arr[i]≤1000000000)。
输出描述:
输出一个整数,表示组成aim的最小货币数,无解时输出-1.
#include<iostream>
#include<vector>
using namespace std;
int coins(vector<int> arr, int aim){
if(arr.empty()||aim<0) {
return -1;
}
int n = arr.size();
vector<int> dp(aim+1, -1);
dp[0]=0;
for(int i=n-1;i>=0;i--){
for(int j = 0;j<=aim; j++){
int diff = j-arr[i];
if(diff>=0 && dp[diff]!=-1){//不越界
dp[j]=dp[j]>0?min(dp[j], dp[diff]+1):dp[diff]+1;
}
}
}
return dp[aim];
}
int main(){
/*
int n, aim;
cin>>n>>aim;
vector<int> arr(n, 0);
cout<<coins1(arr, aim)<<endl;
*/
vector<int> arr={1040,1943,2373,2678,4861,4849,1702,2575,4574,482,3977,1230,2581,3044,2320,615,3170,15,3761,2522,2718,3762,4551,22,2876,4434,2928,496,1296,1986,553,988,4217,3738,4109,425,420,4772,4572,2157,3479,3128,1287,3096,97,1582,780,4744,4654,3595,195,2429,1148,1638,4579,2614,1487,1675,4635,100,233,3923,4449,1598,1949,2349,2153,211,2374,2805,2777,81,2020,963,3272,4594,1480,3666,1170,1010,2432};
cout<<coins(arr, 4917)<<endl;
system("pause");
return 0;
}