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

    https://codesolutiony.wordpress.com/2015/05/24/lintcode-coins-in-a-line-iii/

    A very juicy one! Deserve more consideration.

    class Solution {
    public:
        /**
         * @param values: a vector of integers
         * @return: a boolean which equals to true if the first player will win
         */
        bool firstWillWin(vector<int> &values) {
            int n = values.size();
          if (n < 2) return true;
        
        // Step 1: Find Variables
        //       since it is 2-end a single dim i is not enough, so - i, j (left, right)
        //       and dp[i][j] is the max value Play1 can get in [i, j]
        vector<vector<int>> dp(n, vector<int>(n));
        
        // Step 2: Choice strategy
        //       Apparently in every step, we have 2 choices: pick left or right
        //       so dp[i][j] should depends on dp[i-1][j] and dp[i][j-1]
        //
        // Step 2.5 Game Thoery
        //       In each choice at step2, we always Play2 always made the optimal
        //       choice in last step
        //
        // Equation
        //    dp[i][j] = max(
        //            values[i] + sum[i+1][j] - dp[i+1][j],
        //            values[j] + sum[i][j-1] - dp[i][j-1]
        //              );
        
        vector<int> presum(n);
        partial_sum(values.begin(), values.end(), presum.begin());
        
        for(int j = 0; j < n; j ++)
        for(int i = j; i >= 0; i --)
        {
            if (i == j)
            {
              dp[i][j] = values[i];
            }
            else
            {
              int sumij = presum[j] - (i > 0 ? presum[i - 1] : 0);
              dp[i][j] = sumij - min(dp[i+1][j], dp[i][j-1]);
            }
        }
        
        return dp[0][n-1] > (presum.back() - dp[0][n-1]);
        }
    };
  • 相关阅读:
    npm私服包管理-发布
    搭建npm私服
    vue.js框架搭建
    基于cropper实现图片上传,剪切,下载
    base64转图片
    获取file的路径
    如何制定好测试策略(一)
    让测试团队慢慢死去!-有同感,转载
    2016-2016自动化测试的趋势
    2016-安全性测试
  • 原文地址:https://www.cnblogs.com/tonix/p/4966431.html
Copyright © 2011-2022 走看看