[LeetCode]486. Predict the Winner

来源:互联网 发布:淘宝美国兔妈是真货吗 编辑:程序博客网 时间:2024/05/16 18:41

https://leetcode.com/problems/predict-the-winner/

给一个int数组,两个人依次从数组任意一头拿一个数,判断player1最后拿到的总数是否更大



两人依次拿,如果P1赢,则P1拿的>P2拿的。我们把P1拿的视为“+”,把P2拿的视为“-”,如果最后结果大于等于0则P1赢。

因此对于递归来说,beg ~ end的结果为max(nums[beg] - partition(beg + 1, end), nums[end] - partition(beg, end + 1));对于非递归来说DP[beg][end]表示即为beg ~ end所取的值的大小(最终与零比较)

本题两解:

递归:

public class Solution {    public boolean PredictTheWinner(int[] nums) {        int ret = partition(nums, 0, nums.length - 1, new Integer[nums.length][nums.length]);        return ret >= 0;    }    private int partition(int[] nums, int beg, int end, Integer[][] cache) {        if (cache[beg][end] == null) {            cache[beg][end] = beg == end ? nums[beg] : Math.max(nums[beg] - partition(nums, beg + 1, end, cache), nums[end] - partition(nums, beg, end - 1, cache));        }        return cache[beg][end];    }}


非递归:

public class Solution {    public boolean PredictTheWinner(int[] nums) {    if (nums == null || nums.length == 0) {    return false;    }    int[][] dp = new int[nums.length][nums.length];    int sum = 0;    for (int num : nums) {    sum += num;    }    for (int i = 0; i < nums.length; i++) {    dp[i][i] = nums[i];    }    for (int i = nums.length - 2; i >= 0; i--) {    for (int j = i + 1; j < nums.length; j++) {    dp[i][j] = Math.max(nums[i] - dp[i + 1][j], nums[j] - dp[i][j - 1]);    }    }    return dp[0][nums.length - 1] >= 0;    }}


0 0