華為OJ 初級:24點遊戲演算法
阿新 • • 發佈:2019-02-09
描述 |
問題描述:給出4個1-10的數字,通過加減乘除,得到數字為24就算勝利 |
---|---|
知識點 | 迴圈 |
執行時間限制 | 10M |
記憶體限制 | 128 |
輸入 |
輸入4個int整數 |
輸出 |
返回能否得到24點,能輸出true,不能輸出false |
樣例輸入 | 7 2 1 10 |
樣例輸出 | true |
/*本題使用遞迴的方法 * */ import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int[] nums = new int[4]; for (int i = 0; i < 4; i++) nums[i] = sc.nextInt(); sc.close(); System.out.println(getResult(nums, 0, 0)); } private static boolean getResult(int[] nums, int i, int result) { if (result == 24) return true; if (i < 4) { //加減乘除四種運算,只要其中一種返回true則運算結束,當result=0時,乘除的運算直接返回0 return getResult(nums, i + 1, result + nums[i]) || getResult(nums, i + 1, result - nums[i]) || getResult(nums, i + 1, result == 0 ? 0 : result * nums[i]) || getResult(nums, i + 1, result == 0 ? 0 : result / nums[i]); } else return false; } }