【華為機試067】24點遊戲演算法
阿新 • • 發佈:2018-12-24
題目描述:
給出4個1-10的數字,通過加減乘除,得到數字為24就算勝利
輸入:
4個1-10的數字。[數字允許重複,但每個數字僅允許使用一次,測試用例保證無異常數字]
輸出:
true or false
Java實現:
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String line = sc.nextLine(); String[] strs = line.split(" "); List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < 4; i++) { list.add(Integer.parseInt(strs[i])); } boolean flag = fun(list); System.out.println(flag); } } public static boolean fun(List<Integer> list) { for (int i = 0; i < list.size(); i++) { int temp = list.get(i); list.remove(i); if (getResult(list, temp)) { return true; } list.add(i, temp); } return false; } public static boolean getResult(List<Integer> list, int temp) { if (list.size() > 0) { for (int i = 0; i < list.size(); i++) { int n = list.get(i); list.remove(i); if (getResult(list, temp * n) || getResult(list, temp + n) || getResult(list, temp - n)) { return true; } else if (temp % n == 0) { if (getResult(list, temp / n)) { return true; } } list.add(i, n); } return false; } else { if (temp == 24) { return true; } else { return false; } } } }
知識點:
- DFS深度優先搜尋,確定一個運算子就不停使用,直到最終返回false或true
- 從list中移除一個元素後,如果深度搜索後沒有找到,還要把它添加回去