题解 | #HJ067 24点游戏算法#

24点游戏算法

http://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb

import java.util.Scanner;

/**
 * HJ67 24点游戏算法 - 中等
 */ 
public class HJ067 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String str = sc.nextLine();
            boolean result = getResult(str);
            System.out.println(result);
        }
        sc.close();
    }

    private static boolean getResult(String str) {
        String[] numstr = str.split(" ");
        int[] nums = new int[4]; // 存放数字
        int[] visit = new int[4]; // 存放对应位置数字的使用状态(1代表已使用)
        boolean flag = false;
        for (int i = 0; i < 4; i++) {
            nums[i] = Integer.parseInt(numstr[i]); // 读取数字
        }
        for (int i = 0; i < 4; i++) {
            visit[i] = 1; // 把当前数字标记为已使用
            if (dfs(nums, visit, nums[i])) { // 进入递归
                flag = true;
                break;
            }
        }
        return flag;
    }

    /**
     *
     * @param nums 所有的数字
     * @param visit 所有的数字是否已使用
     * @param temp 数字之和
     * @return
     */
    public static boolean dfs(int[] nums, int[] visit, int temp) {
        for (int i = 0; i < nums.length; i++) {
            if (visit[i] == 0) { // 如果是未使用的数字
                visit[i] = 1; // 标记为已使用
                if (dfs(nums, visit, temp + nums[i]) // 递归判断
                        || dfs(nums, visit, temp - nums[i])
                        || dfs(nums, visit, temp * nums[i])
                        || (temp % nums[i] == 0 && dfs(nums, visit, temp / nums[i]))) {
                    // 如果存在满足条件的,终止循环
                    return true;
                }
                // 不存在满足条件的,说明当前的数字顺序不符要求,进行回溯,把标记重置为0
                visit[i] = 0;
            }
        }
        // 数字都已使用且结果为24,返回真,不存在24,返回假
        return temp == 24;
    }

}
全部评论

相关推荐

2025-12-28 22:19
门头沟学院 Java
不敢追165女神:简历写得毫无特点,你说你要是大二或者大三找寒假实习到暑期实习这段时间,你的简历还能约到面试。但是你是研究生哥,面试官不会因为你是研究生而降低要求,反而会觉得你是研究生才学了这么一点?为什么我不找个同阶段的本科生?
简历中的项目经历要怎么写
点赞 评论 收藏
分享
评论
4
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务