LintCode Coins in a Line III

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

题目:

There are n coins in a line. Two players take turns to take a coin from one of the ends of the line until there are no more coins left. The player with the larger amount of money wins.

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

Example

Given array A = [3,2,2], return true.

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

Given array A = [1,20,4], return false.

题解:

类似Coins in a Line II.

DP问题. 状态dp[l][r]第i到第j的硬币时,先手去硬币的人最后最多去硬币价值.

转移方程, pickLeft = min(dp[l+2][r], dp[l+1][r-1])+values[l]

     pickRight = min(dp[l][r-2], dp[l-1][r-1])+values[r]

     dp[l][r] = max(pickLeft, pickRight)

初始化l == r时, dp[l][r] = values[l]

        l+1 == r时, dp[l][r] = max(values[l], values[l+1])

答案dp[0][values.length-1] > sum/2

Time Complexity: O(n^2), 有n^2个状态需要去计算. Space: O(n^2).

AC Java:

 1 public class Solution {
 2     /**
 3      * @param values: an array of integers
 4      * @return: a boolean which equals to true if the first player will win
 5      */
 6     public boolean firstWillWin(int[] values) {
 7         if(values == null || values.length == 0){
 8             return false;
 9         }
10         
11         int n = values.length;
12         int [][] dp = new int[n][n];
13         boolean [][] used = new boolean[n][n];
14         int sum = 0;
15         for(int val : values){
16             sum += val;
17         }
18         return sum < 2*memorySearch(values, 0, values.length-1, dp, used);
19     }
20     
21     private int memorySearch(int [] values, int l, int r, int [][] dp, boolean [][] used){
22         if(used[l][r]){
23             return dp[l][r];
24         }
25         used[l][r] = true;
26         if(l>r){
27             dp[l][r] = 0;
28         }else if(l == r){
29             dp[l][r] = values[l];
30         }else if(l + 1 == r){
31             dp[l][r] = Math.max(values[l], values[l+1]);
32         }else{
33             int pickLeft = Math.min(memorySearch(values, l+2, r, dp, used), memorySearch(values, l+1, r-1, dp, used)) + values[l];
34             int pickRight = Math.min(memorySearch(values, l+1, r-1, dp, used), memorySearch(values, l, r-2, dp, used)) + values[r];
35             dp[l][r] = Math.max(pickLeft, pickRight);
36         }
37         return dp[l][r];
38     }
39 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/6410366.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值