拼凑面额

牛客网题目
公司:美团
类型:搜索 记忆化递归
难度:中等
题意:从6个固定面值中找出凑成给定面值大小的种数,每个面值可以用无数次。可以用深度搜索,选0到n次,然后回溯。可以使用数组/map保存计算过的值,结果可能超过int所以用long long保存。

版本1

使用数组保存,执行时间31ms

#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <string>
#include <unordered_map>
#include <map>
using namespace std;
typedef long long ll;
const int N = 1e4+5;
ll arr[6]={100, 50, 20, 10, 5, 1}, n;
ll dp[7][N];
ll dfs(ll u, ll cur){
	ll t = cur;
	if(dp[u][cur] != -1) return dp[u][cur];
	if(u==6){
		if(!cur) return 1;
		return 0;
	}
	ll res = 0;
	res += dfs(u+1, cur); 
	while(cur>=arr[u]){ 
		cur -= arr[u];
		res += dfs(u+1, cur);
	}
	dp[u][t] = res;
	return res;
}
int main(){
	cin>>n;
	memset(dp, -1, sizeof dp);
	cout<<dfs(0, n)<<endl;
	return 0;
} 

版本2

使用map保存331ms

#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <string>
#include <unordered_map>
#include <map>
using namespace std;
typedef long long ll;
const int N = 1e4+5;
int arr[6]={100, 50, 20, 10, 5, 1}, n;
map<pair<int, int>, ll> mp;

ll dfs(int u, int cur){
	pair<int, int> v = make_pair(u, cur);
	if(mp.count(v)) return mp[v]; 
	if(u==6){
		if(!cur) return 1;
		return 0;
	}
	ll res = 0;
	res += dfs(u+1, cur); //一个都不选 
	while(cur>=arr[u]){ //暴力凑超时AC70%
		cur -= arr[u];
		res += dfs(u+1, cur);
	}
	mp[v] = res;
    return res;
}
int main(){
	cin>>n;
    mp.clear();
	cout<<dfs(0, n)<<endl;
	return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值