877. Stone Game - LeetCode

Question

877. Stone Gamejava

Solution

题目大意:算法

说有偶数个数字,alex和lee两我的比赛,每次轮流从第一个数字或最后一个数字中拿走一个(偶数个数字,因此他俩拿的数字个数相同),最后比谁拿的数字总和大。题目是让咱们设计一个算法,对于任意给定的一系列数字,判断若是alex先选,是否必定赢(全部数加起来是奇数,因此不存在平局)?设计

思路:code

朴素的暴力递归全部可能的走法,回归的时候只贪心地保留更优的那个解就能够了。而后对于可能的重复的子问题,用一个表储存以前全部解决过的子问题解(动态规划)就能够避免指数级增加的复杂度。递归

Java实现:ip

public boolean stoneGame(int[] piles) {
	return true;
}

动态规划实现:leetcode

class Solution {

    public boolean stoneGame(int[] piles) {
        p = piles;
        int len = piles.length;
        dp = new int[len][len];
        return dp(0,len-1) > 0;
    }

    private int[] p;        //copy of piles
    private int[][] dp;     //solved subproblems

    private int dp(int lo, int hi) {
        if (lo == hi) {  
            return 0; 
        }
        if (dp[lo][hi] != 0) { 
            return dp[lo][hi]; 
        }
        int res = 0;
        if ((hi - lo + 1) % 2 == 0) {
            res = Math.max(dp(lo+1,hi) + p[lo], dp(lo,hi-1) + p[hi]);
        } else {
            res = Math.min(dp(lo+1,hi) - p[lo], dp(lo,hi-1) - p[hi]);
        }
        dp[lo][hi] = res;
        return res;
    }
}

Ref

你们都见过哪些让你虎躯一震的代码? - 知乎get

相关文章
相关标签/搜索