java 486.预测获胜者(Minimax).java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 486.预测获胜者(Minimax).java相关的知识,希望对你有一定的参考价值。

public class Solution {
    public boolean PredictTheWinner(int[] nums) {
        int[] dp = new int[nums.length];
        for (int s = nums.length; s >= 0; s--) {
            for (int e = s + 1; e < nums.length; e++) {
                int a = nums[s] - dp[e];
                int b = nums[e] - dp[e - 1];
                dp[e] = Math.max(a, b);
            }
        }
        return dp[nums.length - 1] >= 0;
    }
}
public class Solution {
    public boolean PredictTheWinner(int[] nums) {
        int[][] dp = new int[nums.length + 1][nums.length];
        for (int s = nums.length; s >= 0; s--) {
            for (int e = s + 1; e < nums.length; e++) {
                int a = nums[s] - dp[s + 1][e];
                int b = nums[e] - dp[s][e - 1];
                dp[s][e] = Math.max(a, b);
            }
        }
        return dp[0][nums.length - 1] >= 0;
    }
}
public class Solution {
    public boolean PredictTheWinner(int[] nums) {
        Integer[][] memo = new Integer[nums.length][nums.length];
        return winner(nums, 0, nums.length - 1, memo) >= 0;
    }
    public int winner(int[] nums, int s, int e, Integer[][] memo) {
        if (s == e)
            return nums[s];
        if (memo[s][e] != null)
            return memo[s][e];
        int a = nums[s] - winner(nums, s + 1, e, memo);
        int b = nums[e] - winner(nums, s, e - 1, memo);
        memo[s][e] = Math.max(a, b);
        return memo[s][e];
    }
}486. Predict the Winner
class Solution {
    private int helper(int[] nums, int s, int e, int turn) {
        if (s == e) {
            return turn * nums[s];
        } 
        int a = turn * nums[s] + helper(nums, s + 1, e, -turn);
        int b = turn * nums[e] + helper(nums, s, e - 1, -turn);
        return turn * Math.max(turn * a, turn * b);
    } 
    public boolean PredictTheWinner(int[] nums) {
        if(nums == null || nums.length < 1) return false;
        int len = nums.length;
        //Special Case
        if (len % 2 == 0) {
            int odd = 0, even = 0;
            for (int i = 0; i < len; i++) {
                if (i % 2 == 0) {
                    even += nums[i];
                } else {
                    odd += nums[i];
                }
            }
            if (odd != even) return true;
        }
        
        // 
        return helper(nums, 0, nums.length - 1, 1) >= 0;
        
        
    }
}

以上是关于java 486.预测获胜者(Minimax).java的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode]Minimax-486. Predict the Winner

486. 预测赢家

LeetCode 486. 预测赢家

leetcode 486 预测赢家

[PKUWC2018]Minimax

loj#2537. 「PKUWC2018」Minimax