24点游戏算法, 华为, 全排列

生成4个数的全排列, 和3个操作符的全排列,判断是否运算结果为24。

import java.util.*;
public class Main {
    static boolean res;
    static boolean is24(int[] a, int n, char[] op) {
        int res = a[0];
        for(int i=1; i < n; i++) {
            if(op[i-1] == '+') res += a[i];
            else if(op[i-1] == '-') res -= a[i];
            else if(op[i-1] == '*') res *= a[i];
            else if(a[i] == 0 || res % a[i] != 0) return false;
            else res /= a[i];
        }
        return res == 24;
    }
    static void dfs(int[] a, int n, char[] op, int u){
        if(u == n) {
            if(is24(a, n, op)) 
                res = true;
            return ;
        } 
        for(int i=u; i < n; i++) {
            int t = a[i]; a[i] = a[u]; a[u] = t;
            dfs(a, n, op, u+1);
            t = a[i]; a[i] = a[u]; a[u] = t;
        }
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()) {
            int a = sc.nextInt(), b = sc.nextInt();
            int c = sc.nextInt(), d = sc.nextInt();
            int[] arr = new int[] {a, b, c, d}; 
            char[] op = new char[] {'+', '-', '*', '/'};
            res = false;
            for(int i=0; i < 4; i++) {
                for(int j=0; j < 4; j++) {
                    for(int k=0; k < 4; k++) {
                        char[] t = new char[] {op[i],op[j],op[k]}; 
                        dfs(arr, 4, t, 0);
                        if(res == true){
                            i = j = k = 5; // break;
                        }
                    }
                }
            }
            System.out.println(res);
        }
    }
}

posted @ 2020-07-07 17:54  li修远  阅读(204)  评论(0编辑  收藏  举报