zoukankan      html  css  js  c++  java
  • LintCode Coins in a Line

    原题链接在这里:http://www.lintcode.com/en/problem/coins-in-a-line/

    题目:

    There are n coins in a line. Two players take turns to take one or two coins from right side until there are no more coins left. The player who take the last coin wins.

    Could you please decide the first play will win or lose?

    Example

    n = 1, return true.

    n = 2, return true.

    n = 3, return false.

    n = 4, return true.

    n = 5, return true.

    题解:

    类似Nim Game. 这道题其实是DP, 后面还有进阶题.

    状态 还剩i个coin时先手的人是赢是输.

    转移方程 dp[i] = (dp[i-2] && dp[i-3]) || (dp[i-3] && dp[i-4]).

    初始化 dp[0] = false, dp[1] = true, dp[2] = true, dp[3] = false.

    答案dp[n].

    Time Complexity: O(n), 因为中间用了dp来记录中间值. Space: O(n), stack space.

    AC Java:

     1 public class Solution {
     2     public boolean firstWillWin(int n) {
     3         int [] dp = new int[n+1];
     4         return memorySearch(n, dp);
     5     }
     6     
     7     private boolean memorySearch(int n, int [] dp){
     8         if(dp[n] != 0){
     9             return dp[n] == 2;
    10         }
    11         
    12         if(n<=0 || n == 3){
    13             dp[n] = 1;
    14         }else if(n == 1 || n == 2){
    15             dp[n] = 2;
    16         }else{
    17             if((memorySearch(n-2, dp) && memorySearch(n-3, dp)) 
    18                 || (memorySearch(n-3, dp) && memorySearch(n-4, dp))){
    19                     dp[n] = 2;
    20                 }else{
    21                     dp[n] = 1;
    22                 }
    23         }
    24 
    25         if(dp[n] == 2){
    26             return true;
    27         }else{
    28             return false;
    29         }
    30     }
    31 }

     跟上Coins in a Line II.

  • 相关阅读:
    csrf跨站请求伪造
    IO 之 InputStream 和 Reader
    javadoc tags
    java this
    递归
    java 文件中 定义一个字符串,它的默认编码是什么?
    合并数组
    << 移位运算
    final static T
    Base64.java 工具类
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/6406922.html
Copyright © 2011-2022 走看看