//#include<bits/stdc++.h> 没有vector
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
/*问题描述:arr中是面币的数值大小,eg:arr=={1,2,5,10,20,100}元等 要凑齐325元,有多少种方法? */
//作用:返回 可以自由使用arr[index...]及其以后的所有面值,每种面值可以使用任意张组成rest的方法
//决策转换成了当前使用arr[index]的张数0-arr[index]*zhang<=rest
int processing(vector<int>arr, int index, int rext) {
//if (rext < 0) return 0; 可以不要 因为for循环中已经保障此条件必定不满足
if (index == arr.size()) return rext == 0 ? 1 : 0;
int numway = 0;
for (int zhang = 0; zhang*arr[index] <= rext; zhang++) {
numway += processing(arr, index + 1, rext - zhang*arr[index]);
}
return numway;
}
int processing2(vector<int>arr, int index, int rext,vector<vector<int>>&dp) {
//if (rext < 0) return 0;可以不要 因为for循环中已经保障此条件必定不满足
if (dp[index][rext] != -1) {
return dp[index][rext];
}
if (index == arr.size()) {
dp[index][rext] = rext == 0 ? 1 : 0;
return dp[index][rext];
}
int numway = 0;
for (int zhang = 0; zhang*arr[index] <= rext; zhang++) {
numway += processing(arr, index + 1, rext - zhang*arr[index]);
}
dp[index][rext] = numway;
return dp[index][rext];
}
int processing3(vector<int>arr, int composedmoney) {
//if (rext < 0) return 0;可以不要 因为for循环中已经保障此条件必定不满足
vector<vector<int>>dp;
dp.resize(arr.size() + 1, vector<int>(composedmoney + 1, 0));
dp[arr.size()][0] = 1;//dp初始化是就定义为0;所以不用填其他情况
for (int index = arr.size()-1; index >= 0; index--) {
for (int rest = 0; rest <= composedmoney; rest++) {
int numway = 0;
for (int zhang = 0; zhang*arr[index] <= rest; zhang++) {
numway += dp[ index + 1][ rest - zhang*arr[index]];
}
dp[index][rest] = numway;
}
}
return dp[0][composedmoney];
}
int processing4(vector<int>arr, int composedmoney) {
//if (rext < 0) return 0;可以不要 因为for循环中已经保障此条件必定不满足
vector<vector<int>>dp;
dp.resize(arr.size() + 1, vector<int>(composedmoney + 1, 0));
dp[arr.size()][0] = 1;//dp初始化是就定义为0;所以不用填其他情况
for (int index = arr.size() - 1; index >= 0; index--) {
for (int rest = 0; rest <= composedmoney; rest++) {
dp[index][rest] = dp[index + 1][rest];
if (rest - arr[index] >= 0) {
dp[index][rest] += dp[index][rest - arr[index]]; //666消除了枚举过程的dp
}
}
}
return dp[0][composedmoney];
}
int main() {
vector<int>money = { 1, 2, 5, 10, 20, 50, 100 };
int composedmoney = 100;
cout << processing(money, 0, composedmoney) << endl; //暴力递归
vector<vector<int>>dp;
dp.resize(money.size() + 1, vector<int>(composedmoney + 1, -1));
cout << processing2(money, 0, composedmoney,dp) << endl; //记忆化搜索
cout << processing3(money, composedmoney) << endl; //dp
cout << processing4(money, composedmoney) << endl; //dp
system("pause");
return 0;
}
拼凑面币
最新推荐文章于 2021-11-25 22:33:49 发布