火柴棍能组成的最大数字

火柴棍能组成的最大数字

2020春招百度笔试题

题目:

输入火柴棍根数n,能选取的数字个数m,以及能选取的数字列表
输入案例(原题案例我忘了,瞎写的)
20 4
5 6 7 8
输出能组成的最大整数值

题解:使用动态规划,代码github链接 ,如有错误还望指出,新手上路,请多关照

#include <cstdio>
#include <cmath>
#include <vector>

using namespace std;
int number[10] = { 0,1,2,3,4,5,6,7,8,9 };
int expend[10] = { 0,2,5,5,4,5,6,3,7,6 };
int main() {
	int n, m;
	scanf("%d", &n);
	scanf("%d", &m);
	vector<bool> canuse(10, false);
	vector<int> dp(n+1,0);
	for (int i = 0; i<m; i++) {
		int temp;
		scanf("%d", &temp);
		canuse[temp] = true;
	}
	dp[0]=0;
	for(int i=1;i<=n;i++){
		int choice=0;
		int maxvalue=0;
		for(int j=1;j<=9;j++){
			if(canuse[j]) {
				if(i-expend[j]<0) continue;
				if(dp[i-expend[j]]==-1) continue;
				if(dp[i-expend[j]]>=maxvalue){
					choice=j;
					maxvalue=dp[i-expend[j]];
				}
			}
		}
		if(choice==0) dp[i]=-1;
		else{
			dp[i]=maxvalue*10+choice;
		}
		//printf("%d\n",dp[i]);
	}
	printf("%d",dp[n]);
	return 0;
}

2020年3月14日

发布了15 篇原创文章 · 获赞 5 · 访问量 3673

猜你喜欢

转载自blog.csdn.net/qq_28632981/article/details/104871619