---
title: "Number of ways to represent money"
author: "standalone"
date: "2012-09-03T11:34:00Z"
tags: []
categories: ["编程语言"]
slug: "number-of-ways-to-represent-money"
draft: false
lastmod: "2012-09-03T11:34:40Z"
id: 1670164
url: "https://standalone.iteye.com/blog/1670164"
---

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:

```java

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:

```java

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


```