[LeetCode]486. Predict the Winner

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值