LeetCode679-20.8.22-24点游戏

链接LeetCode679
过程:以前做过,快忘记了,枚举所有可能的情况,判断一下就行
思路:用回溯来枚举状态
代码

class Solution {
    public boolean judgePoint24(int[] nums) {
        int[] hh=new int[4];
        for(int i=0;i<4;i++)hh[i]=1;
        return dfs(nums,hh);
    }
    boolean dfs(int[] a,int[] b){
        int n=a.length;
        if(n==1){
            if(a[0]%b[0]==0&&a[0]/b[0]==24)return true;
            return false;
        }
        int[] ha=new int[n-1];
        int[] hb=new int[n-1];
        int cnt;
        for(int i=0;i<n;i++){
            for(int j=i+1;j<n;j++){
                cnt=0;
                for(int k=0;k<n;k++){
                    if(k!=i&&k!=j){
                        ha[cnt]=a[k];
                        hb[cnt]=b[k];
                        cnt++;
                    }
                }
                ha[cnt] = a[i] * b[j] + a[j] * b[i];
                hb[cnt] = b[i] * b[j];
                if (hb[cnt]!=0&&dfs(ha, hb)) return true;
                ha[cnt] = a[i] * b[j] - a[j] * b[i];
                hb[cnt] = b[i] * b[j];
                if (hb[cnt]!=0&&dfs(ha, hb)) return true;
                ha[cnt] = a[j] * b[i] - a[i] * b[j];
                hb[cnt] = b[i] * b[j];
                if (hb[cnt]!=0&&dfs(ha, hb)) return true;
                ha[cnt] = a[i] * a[j];
                hb[cnt] = b[i] * b[j];
                if (hb[cnt]!=0&&dfs(ha, hb)) return true;
                ha[cnt] = a[i] * b[j];
                hb[cnt] = b[i] * a[j];
                if (hb[cnt] != 0 && dfs(ha, hb)) return true;
                ha[cnt] = a[j] * b[i];
                hb[cnt] = b[j] * a[i];
                if (hb[cnt] != 0 && dfs(ha, hb)) return true;
            }
        }
        return false;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值