硬币找零java_Java中的硬币找零问题及解决方案

硬币找零java

Problem:

问题:

You are working at the cash counter at a fun-fair, and you have different types of coins available to you in infinite quantities. The value of each coin is already given. Can you determine the number of ways of making change for a particular number of units using the given types of coins?

您正在一个游乐场上的收银台工作,并且可以无限量使用不同类型的硬币。 每个硬币的价值已经给出。 您能确定使用给定类型的硬币对特定数量单位进行更改的方式数量吗?

Example:

例:

If you have 3 types of coins, and the value of each type is given as 1,2,3 respectively, you can make change for 4 units in four ways:

如果您有3种硬币,并且每种硬币的价值分别为1,2,3,则可以用以下四种方法更改4个单位:

    {1,1,1,1}  
    {1,1,2}     
    {1,3}       
    {2,2}       

    Distribute as total sum is 4.

    f(4)=1+f(3)
    f(4)=2+f(2)
    f(4)=3+f(1)      
    f(3)=1+f(2) and so on

Solution code (java code):

解决方案代码(java代码):

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
	static long[][]  memo;
	static long count(int i,long coin[],int j){
		if(i==0)
			return 1;
		if(i<0)
			return 0;
		if(j<=0) 
			return 0;
		if(memo[i][j]!=-1) 
			return memo[i][j];
		memo[i][j]=count(i,coin,j-1)+count(i-(int)coin[j-1],coin,j);  
		//memo[i][j]=memo[i][j-1]+memo[i-value(c[j-1])][j] 
		//where  0<=j<=m hence j-1 is used.
		//for example if c[]=1,2,3 and n=4 then 
		//memo[4][3]=memo[4][2]+memo[4- value(c[2]])][3]
		//i.e. memo[4][3]=memo[4][2]+memo[1][3]
		return memo[i][j];
	}
	
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int m = in.nextInt();
		long c[]=new long[m];
		
		memo=new long[n+1][m+1];
		
		for(int i=0;i<=n;i++)
			for(int j=0;j<=m;j++) 
				memo[i][j]=-1;
		for(int c_i=0; c_i < m; c_i++){
			c[c_i] = in.nextLong();
		}
		long ways=count(n,c,m);
		// Print the number of ways of making change for 'n' 
		//units using coins having the values given by 'c'
		System.out.println(ways);
	}
}

Output

输出量

Output - coin problem and solution in java

翻译自: https://www.includehelp.com/java/coin-change-problem-and-solution.aspx

硬币找零java

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值