思路:动态规划的思路
新建一个二维数组来存储结果
动态方程 dp[0][j]=0 dp[i][0]=1
if j-price[i-1]<0: dp[i][j]=dp[i-1][j]
else: dp[i][j]=dp[i][i-price[i-1]]+dp[i-1][j]
如下说是
0 1 2 3 4 5 6 7 8 9 10
0 1 0 0 0 0 0 0 0 0 0 0
2 1 0 1 0 1 0 1 0 1 0 1
3 1 0 1 1 1 1 2 1 2 2 2
5 1 0 1 1 1 2 2 2 3 3 4
代码如下:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
int money;
cin>>money;
string str;
cin>>str;
vector<int>price;
int left=1;
//对于价格的输入处理
for(int i=1;i<str.length();i++){
if(str[i]==','){
price.push_back(stoi(str.substr(left,i-left)));
left=i+1;
}
}
price.push_back(stoi(str.substr(left,str.length()-left-1)));
//对价格进行从小到大的排序
sort(price.begin(),price.end());
//获取价格的种类
int price_length=price.size();
//动态规划存放结果
vector<vector<int>>temp(price_length+1,vector<int>(money+1,0));
//没有价格的时候有钱也没有办法,故为0
for(int i=0;i<=money;i++){
temp[0][i]=0;
}
//没有钱的时候都是1种选法
for(int i=0;i<=price_length;i++){
temp[i][0]=1;
}
//进行动态规划遍历
for(int i=1;i<=price_length;i++){
for(int j=1;j<=money;j++){
//如果加入该价格之后,当前的钱小于该价格,则该价格对该钱不起作用,还是之前的种数
if(j-price[i-1]<0) temp[i][j]=temp[i-1][j];
//如果大于该价格,则价格对于起作用,减掉该价格之后的方案数+不需要该价格的方案数即可
else temp[i][j]=temp[i][j-price[i-1]]+temp[i-1][j];
}
}
cout<<temp[price_length][money]<<endl;
}