java 679. 24 Game.java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 679. 24 Game.java相关的知识,希望对你有一定的参考价值。

class Solution {
    char[] ops = new char[]{'+','-','*','/'};
    
    public boolean judgePoint24(int[] nums) {
        List<Double> list = new ArrayList<>();
        for (int num: nums)
            list.add(1.0 * num);
        
        return search(list);
    }
    
    private boolean search(List<Double> list){
        if (list.size()==1){
            return list.get(0)==24.0;
        }
        
        List<Double> tmp = new ArrayList<>();
        for (int i=0; i<list.size(); i++)
            for (int j=0; j<list.size(); j++)
                if (i!=j){
                    for (char op: ops){
                        if ((op=='+' || op=='*') && (i>j)) continue;
                        if (op=='/' && list.get(j)==0.0) continue;
                        double res = 0.0;
                        switch(op){
                            case '+': res = list.get(i) + list.get(j);
                                      break;
                            case '-': res = list.get(i) - list.get(j);
                                      break;
                            case '*': res = list.get(i) * list.get(j);
                                      break;
                            case '/': res = list.get(i) / list.get(j);
                                      break;
                        }
                        
                        tmp.clear();
                        tmp.add(res);
                        for (int k=0;k<list.size();k++)
                            if (k!=i && k!=j)
                                tmp.add(list.get(k));
                        
                        boolean tmpRes = search(tmp);
                        if (tmpRes)
                            return true;
                    }
                }
        
        return false;
    }
}

以上是关于java 679. 24 Game.java的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 679. 24 Game

[LeetCode] 679. 24 Game(回溯法)

LeetCode题679 —— 24 Game

Leetcode之深度优先搜索&回溯专题-679. 24 点游戏(24 Game)

Leetcode 679.24点游戏

leetcode679. 24 Game