1,2,5,10 面额的纸币,考虑顺序情况下组成10元的方法
2022-05-13 16:55 钟铧若岩 阅读(223) 评论(0) 编辑 收藏 举报
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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
2015-05-13 WINDOWS权限大牛们,请进