Number of ways to represent money

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

你可能感兴趣的:(Algorithm)