zoukankan      html  css  js  c++  java
  • 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);
            }
        }
    }
    
    
  • 相关阅读:
    HDFS面试准备
    大数据learn---准备复试
    spring和springMVC的整合
    jsp前端语言
    my_SpringMVC_learning
    代理类学习
    my-spring-learing(AOP)
    django安装配置及测试
    IOS学习之路五(代码实现UITableView)
    IOS7配置自动布局的约束
  • 原文地址:https://www.cnblogs.com/lixyuan/p/13262279.html
Copyright © 2011-2022 走看看