Coins Java 走地牙 CTCI 8.11

package com.company;

/*
* Coins: Given an infinite number of quarters (25 cents), dimes (1O cents),
* nickels (5 cents), and pennies (1 cent), write code to calculate the number of ways of representing n cents.
* */
public class Main {

    public static void main(String[] args) {
   // write your code here
        int[] coins = new int[] {25, 10, 5, 1};
        int n = 100;
        int[][] memo = new int[n + 1][coins.length];
        int index = 0;//index must > 0 && < coins.length;
        System.out.println(findWay(n, coins, memo, index));
    }

    public static int findWay(int n , int[] coins, int[][] memo, int index) {
        if(memo[n][index] != 0) {
            return memo[n][index];
        }
        if(index >= coins.length - 1) {
            return 1;
        }

        int way = 0;
        for(int i = 0; i * coins[index] <= n; i++) {
            int remain = n - i * coins[index];
            way += findWay(remain, coins, memo, index + 1);
        }
        memo[n][index] = way;
        return way;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章