石子游戏 II
题目描述
爱丽丝和鲍勃继续他们的石子游戏。许多堆石子 排成一行,每堆都有正整数颗石子 piles[i]。游戏以谁手中的石子最多来决出胜负。
爱丽丝和鲍勃轮流进行,爱丽丝先开始。最初,M = 1。
在每个玩家的回合中,该玩家可以拿走剩下的 前 X 堆的所有石子,其中 1 <= X <= 2M。然后,令 M = max(M, X)。
游戏一直持续到所有石子都被拿走。
假设爱丽丝和鲍勃都发挥出最佳水平,返回爱丽丝可以得到的最大数量的石头。
样例
样例输入
piles = [2,7,9,4,4]
piles = [1,2,3,4,5,100]
样例输出
10
解释:如果一开始Alice取了一堆,Bob取了两堆,然后Alice再取两堆。爱丽丝可以得到2 + 4 + 4 = 10堆。如果Alice一开始拿走了两堆,那么Bob可以拿走剩下的三堆。在这种情况下,Alice得到2 + 7 = 9堆。返回10,因为它更大。
104
提示
- 1 < = p i l e s . l e n g t h < = 100 1 <= piles.length <= 100 1<=piles.length<=100
- 1 < = p i l e s [ i ] < = 1 0 4 1 <= piles[i] <= 10^4 1<=piles[i]<=104
思路
刚看暂时没啥思路,但如果时间允许是可以进行dfs暴力,然后确定好dfs暴力搜索的参数后,发现可以加上记忆化搜索,直接上记忆化搜索试试,试了之后发现能过。
代码实现
class Solution {
int[] s;
int[][] cache;
public int stoneGameII(int[] piles) {
int n = piles.length;
cache = new int[n - 1][(n + 1) / 4 + 1];
s = new int[n];
for(int i = 0; i < cache.length; i++) Arrays.fill(cache[i], -1);
s[n - 1] = piles[n-1];
for(int i = n - 2; i >= 0; i--){
s[i] = s[i + 1] + piles[i];
}
return dfs(0, 1);
}
private int dfs(int index, int m){
if(index + 2 * m >= s.length) return s[index];
if(cache[index][m] != -1) return cache[index][m];
int ans = Integer.MAX_VALUE;
for(int x = 1; x <= 2 * m; x++){
ans = Math.min(ans, dfs(index + x, Math.max(m, x)));
}
return cache[index][m] = s[index] - ans;
}
}
明后天考试,刷题上就没以前时间花的多。