OJ

LeetCode 679. 24 Games

2018-01-28  本文已影响0人  ciferlv
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {

    boolean flag = false;

    public void search(List<Double> nums) {
        if(flag) return;

        if (nums.size() == 1) {

            if (Math.abs(nums.get(0)-24) < 0.000001) flag = true;
            return;
        }

        int nums_size = nums.size();
        for (int i = 0; i < nums_size; i++) {

            for (int j = i + 1; j < nums_size; j++) {

                double ni = nums.get(i), nj = nums.get(j);

                ArrayList<Double> temp_nums = new ArrayList<>();

                for (int k = 0; k < nums_size; k++) {

                    if( k != i && k != j) temp_nums.add(nums.get(k));
                }

                List<Double> temp_res = new ArrayList<>();
                temp_res.addAll(Arrays.asList(ni + nj, ni * nj, ni - nj, nj - ni, ni / nj, nj / ni));

                for (double t : temp_res) {
                    temp_nums.add(temp_nums.size(), t);
                    search(temp_nums);
                    temp_nums.remove(temp_nums.size()-1);
                }
            }
        }
    }

    public boolean judgePoint24(int[] nums) {

        List<Double> nums_d = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) nums_d.add((double) nums[i]);
        search(nums_d);
        return flag;
    }

    public static void main(String[] args) {

        Solution s = new Solution();
        int[] nums = {1, 1, 1, 1};
//        int[] nums = {4, 1, 8, 7};
        System.out.println(s.judgePoint24(nums));
    }
}
上一篇下一篇

猜你喜欢

热点阅读