Number of ways to represent money

本文介绍了如何通过递归算法计算使用不同面额硬币(如美元的四分之一元、十分之一元、五分之一元和一分元)表示特定金额的组合方式。通过实例代码演示了实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem:

Given an infinite number of quarters (25 cents), dimes (10 cents), nickels (5 cents) and pennies (1 cent), write code to calculate the number of ways of representing n cents.

My code:

package alg;
import java.util.Stack;

public class Coins {
public final int coin[] = {25, 10, 5, 1};

void printAllResult(int n){
Stack<Integer> s = new Stack<Integer> ();
printResult(n, s, 0);
}

void printResult(int n, Stack<Integer> s, int index){
if(n == 0){
System.out.println("Find one result:");
for(Integer a : s){
System.out.print("\t" + a);
}
System.out.println("\n");
return;
}
for(int i=index;i<coin.length; i++){
int v = coin[i];
if(n>=v){
s.push(v);
printResult(n-v, s, i);
s.pop();
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Coins c = new Coins();
c.printAllResult(26);
}

}




Result:

Find one result:
25 1

Find one result:
10 10 5 1

Find one result:
10 10 1 1 1 1 1 1

Find one result:
10 5 5 5 1

Find one result:
10 5 5 1 1 1 1 1 1

Find one result:
10 5 1 1 1 1 1 1 1 1 1 1 1

Find one result:
10 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

Find one result:
5 5 5 5 5 1

Find one result:
5 5 5 5 1 1 1 1 1 1

Find one result:
5 5 5 1 1 1 1 1 1 1 1 1 1 1

Find one result:
5 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

Find one result:
5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

Find one result:
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值