题解 | #24点游戏算法#

24点游戏算法

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

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String[] strs = scan.nextLine().split(" ");
        ArrayList<Integer> nums = new ArrayList<>();
        for (String str : strs) {
            nums.add(Integer.valueOf(str));
        }
        for (int num : nums) {
            ArrayList<Integer> copyArr = new ArrayList<>(nums);
            copyArr.remove(Integer.valueOf(num));
            if (process(copyArr, Double.valueOf(num))) {
                System.out.println("true");
                return;
            }
        }
        System.out.println("false");
    }
    public static boolean process(ArrayList<Integer> nums, double total) {
        if (nums.size() == 0) {
            if ((double) 24 == total) {
                return true;
            } else {
                return false;
            }
        }
        for (int num : nums) {
            ArrayList<Integer> copyArr = new ArrayList<>(nums);
            copyArr.remove(Integer.valueOf(num));
            if (process(copyArr, total + num)) {
                return true;
            }
            if (process(copyArr, total - num)) {
                return true;
            }
            if (process(copyArr, total * num)) {
                return true;
            }
            if (Integer.valueOf(num) != 0) {
                if (process(copyArr, total / num)) {
                    return true;
                }
            }
        }
        return false;
    }
}
全部评论
该牛油正在参与牛客写题解薅羊毛的活动,牛币,周边,京东卡超多奖品放送,活动进入倒计时!快来捡漏啦https://www.nowcoder.com/discuss/888949?source_id=profile_create_nctrack&channel=-1
点赞
送花
回复
分享
发布于 2022-04-27 11:43

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务