【华为机试067】24点游戏算法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HEYIAMCOMING/article/details/81115430

题目描述:

给出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中移除一个元素后,如果深度搜索后没有找到,还要把它添加回去

猜你喜欢

转载自blog.csdn.net/HEYIAMCOMING/article/details/81115430