1,2,5,10 面額的紙幣,考慮順序情況下組成10元的方法
阿新 • • 發佈:2022-05-13
1 package com.company; 2 3 //https://time.geekbang.org/column/article/73511 4 5 import org.junit.Test; 6 7 import java.util.ArrayList; 8 9 public class Lesson5_1 { 10 11 public static long[] rewards = {1, 2, 5, 10}; // 四種面額的紙幣 12 13 /** 14 * @param totalReward-獎賞總金額,result-儲存當前的解 15* @return void 16 * @Description: 使用函式的遞迴(巢狀)呼叫,找出所有可能的獎賞組合 17 */ 18 19 public static int index = 0; 20 21 public static void get(long totalReward, ArrayList<Long> result) { 22 23 // 當totalReward = 0時,證明它是滿足條件的解,結束巢狀呼叫,輸出解 24 if (totalReward == 0) { 25 System.out.print(index++);26 System.out.println(result); 27 return; 28 } 29 // 當totalReward < 0時,證明它不是滿足條件的解,不輸出 30 else if (totalReward < 0) { 31 return; 32 } else { 33 for (int i = 0; i < rewards.length; i++) { 34 ArrayList<Long> newResult = (ArrayList<Long>) (result.clone()); //由於有4種情況,需要clone當前的解並傳入被呼叫的函式 35 newResult.add(rewards[i]); // 記錄當前的選擇,解決一點問題 36 get(totalReward - rewards[i], newResult); // 剩下的問題,留給巢狀呼叫去解決 37 } 38 } 39 40 } 41 42 43 @Test 44 public void Test() { 45 int totalReward = 5; 46 Lesson5_1.get(totalReward, new ArrayList<Long>()); 47 48 } 49 50 51 }