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

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

    题目:

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

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

    Example

    Given values array A = [1,2,2], return true.

    Given A = [1,2,4], return false.

    题解:

    Coins in a Line的进阶题.

    还是DP. 状态dp[i]是还剩i枚硬币,先手的人最后能拿到最多的值.

    转移方程 dp[i] = max(min(dp[i-2],dp[i-3])+values[n-i], min(dp[i-3],dp[i-4])+values[n-i]+values[n-i+1])

    初始化dp[0] = 0, dp[1] = values[i-1], dp[2] = values[i-1]+values[i-2], dp[3] = values[i-2] + values[i-3].

    答案 dp[n] > sum/2

    Time Complexity: O(n). Space: O(n), stack space.

    AC Java:

     1 public class Solution {
     2     public boolean firstWillWin(int[] values) {
     3         if(values == null || values.length == 0){
     4             return false;
     5         }
     6         
     7         int n = values.length;
     8         int [] dp = new int[n+1];
     9         boolean [] used = new boolean [n+1];
    10         int sum = 0;
    11         for(int value : values){
    12             sum += value;
    13         }
    14         
    15         return sum < 2*memorySearch(values, dp, n, used);
    16     }
    17     
    18     private int memorySearch(int [] values, int [] dp, int n, boolean [] used){
    19         if(used[n]){
    20             return dp[n];
    21         }
    22         used[n] = true;
    23         
    24         if(n<=0){
    25             dp[n] = 0;;
    26         }else if(n == 1){
    27             dp[n] = values[values.length-1];
    28         }else if(n == 2){
    29             dp[n] = values[values.length-1] + values[values.length-2];
    30         }else if(n == 3){
    31             dp[n] = values[values.length-2] + values[values.length-3];
    32         }else{
    33             dp[n] = Math.max(
    34                 Math.min(memorySearch(values, dp, n-2, used), memorySearch(values, dp, n-3, used)) + values[values.length-n]
    35                 , Math.min(memorySearch(values, dp, n-3, used), memorySearch(values, dp, n-4, used)) + values[values.length-n] + values[values.length-n+1]
    36                 );
    37         }
    38         return dp[n];
    39     }
    40 }

     跟上Coins in a Line III.

  • 相关阅读:
    DS博客作业04--图
    DS博客作业03--树
    DS博客作业02--栈和队列
    DS博客作业01--线性表
    c博客06-2019-结构体&文件
    C博客作业05--2019-指针
    图书馆查书、借书、还书
    DS博客作业05--查找
    DS博客作业04--图
    DS博客作业03--树
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/6406965.html
Copyright © 2011-2022 走看看