---
# System prepended metadata

title: 0679. 24 Game
tags: [Leetcode, Hard, Backtracking]

---

# 0679. 24 Game
###### tags: `Leetcode` `Hard` `Backtracking`
Link: https://leetcode.com/problems/24-game/description/
## 思路
每次dfs选两张牌 然后用四种运算符算出四个结果
分别加进不同的四个list里面 然后再把剩余的数字分别加进去
再对这四个list进行dfs
## Code
```java=
class Solution {
    public boolean judgePoint24(int[] cards) {
        List<Double> nums = new ArrayList<>();
        for(int i=0; i<cards.length; i++){
            nums.add((double)(cards[i]));
        }
        return dfs(nums);
    }
    private boolean dfs(List<Double> nums){
        if(nums.size()==1){
            if (Math.abs(nums.get(0)- 24.0) < 0.001) {
                return true;
            }
            return false;
        }
        for(int i=0; i<nums.size(); i++){
            for(int j=i+1; j<nums.size(); j++){
                for(double c:compute(nums.get(i), nums.get(j))){
                    List<Double> nextRound = new ArrayList<>();
                    nextRound.add(c);
                    for(int k=0; k<nums.size(); k++){
                        if(k!=i && k!=j) nextRound.add(nums.get(k));
                    }
                    if(dfs(nextRound)) return true;
                }
            }
        }
        return false;
    }
    private List<Double> compute(double a, double b){
        List<Double> res = Arrays.asList(a+b, a-b, b-a, a*b, a/b, b/a);
        return res;
    }
}
```