ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

030货币系统(DP 完全背包问题)

2021-01-28 10:01:18  阅读:172  来源: 互联网

标签:背包 Scanner nextInt int long read static 030 DP


题目描述:

给定 V种货币(单位:元),每种货币使用的次数不限。 不同种类的货币,面值可能是相同的。 现在,要你用这 V种货币凑出 N 元钱,请问共有多少种不同的凑法。

输入格式:

第一行包含两个整数 V和 N。 接下来的若干行,将一共输出 V个整数,每个整数表示一种货币的面值。

输出格式:

输出一个整数,表示所求总方案数。

数据范围:

1≤V≤25,
1≤N≤10000
答案保证在long long范围内。

输入样例:

3 10
1 2 5

输出样例:

10

import java.util.Scanner;

public class Main{
	static int N = 30,M = 10010;
	static long[][] f = new long[N][M];
	static int n,m;
	public  static void main(String[] args) {
		Scanner read = new Scanner(System.in);
		n = read.nextInt();
		m = read.nextInt();
		f[0][0] = 1;
		for(int i = 1; i <= n;i++) {
			int v;//每种货币的面额
			v = read.nextInt();
			for(int j = 0; j <= m;j++) {
				f[i][j] = f[i - 1][j];
				if(j >= v) f[i][j] += f[i][j - v];
			}
		}
		System.out.println(f[n][m]);
	}
}

空间上的优化:将二维降至一维

import java.util.Scanner;

public class Main{
	static int N = 30,M = 10010;
	static long[] f = new long[M];
	static int n,m;
	public  static void main(String[] args) {
		Scanner read = new Scanner(System.in);
		n = read.nextInt();
		m = read.nextInt();
		f[0] = 1;
		for(int i = 1; i <= n;i++) {
			int v;//每种货币的面额
			v = read.nextInt();
			for(int j = v; j <= m;j++) {
				f[j] = f[j] + f[j - v];
			}
		}
		System.out.println(f[m]);
	}
}

标签:背包,Scanner,nextInt,int,long,read,static,030,DP
来源: https://blog.csdn.net/qq_46071321/article/details/113276151

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有