有1元、5元、10元、20元、50元、100元硬幣無數個,問100000元的組合方法有多少個
阿新 • • 發佈:2019-02-09
package com.coolxia.具體; import java.util.ArrayList; class Test1 { static int count = 0; static int fun(int stairs, int max, int[] stragy){ if(stairs < 0) return 0; if(stairs == 0) return 1; int count = 0; for(int i: stragy){ if(i <= max){ count += fun(stairs - i, i, stragy); } } return count; } static ArrayList<Integer> result = new ArrayList<Integer>(); static int findIndex(int[] stragy, int num){ for(int index = 0; index <= stragy.length -1; index++){ if(stragy[index] == num){ return index; } } return -1; } static int fun2(int stairs, int[] stragy){ int sum = 0; int left = stairs; int currentIndex = stragy.length - 1; int count = 0; do{ while(sum < stairs){ result.add(stragy[currentIndex]); sum += stragy[currentIndex]; } if(sum == stairs){count++;} int num = result.remove(result.size()-1); sum -= num; if(result.size() != 0){ if(num == stragy[0]){ while(result.size() != 0 && num == stragy[0]){ num = result.remove(result.size()-1); sum -= num; currentIndex = findIndex(stragy, num) - 1; } }else{ currentIndex = findIndex(stragy, num) - 1; } }else{ currentIndex--; } }while(result.size() != 0 || currentIndex >= 0); return count; } } public class Test{ public static void main(String[] args){ int[] stragy = new int[]{ 1, 2 ,5, 10, 20 , 100}; System.out.println(Test1.fun2(10000,stragy)); } }