拼凑面币

//#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值