[LeetCode]292. Nim Game

来源:互联网 发布:淘宝手机端怎么排名 编辑:程序博客网 时间:2024/05/23 00:06

You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.

Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.

For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.


思路:深搜的话时间肯定会爆掉,然后如果用动规的话,可以用递推式dp[i]=!(dp[i-1]&&dp[i-2]&&dp[i-3]),dp里边是自己在i的时候是否可以赢,这个其实是基于两个动规数组,自己和Nim的,结果最后发现,其实两个人的数组是一样的。。然后就用一个就好,然后用动规是AC不了的,有大数据导致超空间,然后就发现。。其实自己按着这个递推公式推几步就发现,只有n为4的倍数的时候,自己是输的,其他时候都是赢的。。然后就解出来了。。


public class Solution {        public boolean canWinNim(int n) {        if(n%4==0){            return false;        }else{            return true;        }    }    /*    public boolean canWinNim(int n) {        if(n<4){            return true;        }else if(n==4){            return false;        }        boolean dp[]=new boolean[n+1];        dp[1]=true;        dp[2]=true;        dp[3]=true;        dp[4]=false;        for(int i=5;i<n+1;i++){            dp[i]=!(dp[i-1]&&dp[i-2]&&dp[i-3]);        }        return dp[n];    }    */}


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 孩子下笔太重怎么办 小孩子写字太重怎么办 经常对小孩发火怎么办 对小孩发火后悔怎么办 小孩子不喜欢学数学怎么办? 孩子心里素质差怎么办 三年级语文太差怎么办 宝宝一年级很笨怎么办 一年级孩子太笨怎么办 孩子学习脑子笨怎么办 四年级孩子数学差怎么办 中考考不好了怎么办 初中没学高中怎么办 数学基础差该怎么办 三年级数学成绩差怎么办 夫妻差6岁怎么办 初一数学很差劲怎么办 三年级孩子成绩差怎么办 初中数学成绩不好怎么办 大人不会算数学怎么办 小学初数学不好怎么办 初中生数学计算能力差怎么办 初中生数学计算差怎么办 初一数学没救了怎么办 五年级英语不好怎么办 三年级孩子学习差怎么办 孩子三年级学习成绩差怎么办 三年级字写不好怎么办 7小孩表达能力差怎么办 孩子考了低分怎么办 初一考300分怎么办 小学三年级成绩不好怎么办 五年级考几分怎么办 思想晚熟的人怎么办 孩子学不好数学怎么办 做作业速度慢怎么办 孩子碎头发太多怎么办 孩子碎发太多怎么办 孩子的作业太多怎么办 爸爸是乙肝孩子怎么办 孩子出生没有奶怎么办