这作为dp的经典题,回头来看,启发良多。
之前在string 背景的 dp题目中,总结了很多解决dp题目的思维模式与技巧。 主要包括 方向性(向‘之前’ 看,解决之后的问题)。 矩阵提示法,上一行? 上一列的意义,联系实际问题的意义。
这俩道coin的题目,一个一维,一个二维,但实质是一个题目。
关于方向性,不管是前还是后,实质是指向subproblem的。 这俩题的解法核心都是如此,确定final problem,和 subproblem。然后从最小问题一直构建到final problem
那么第一题的final problem是 在位置0的时候,先拿的人能否赢?
第二题的final problem则是,在取 0—n-1 这一段时,先拿的人能否赢?
//启发根源来自于这个题目version2。在version2的基础上,如何能够发现version3的类似解法。
//题目
//There are n coins with different value in a line.
//Two players take turns to take one or two coins from left side until there are no more coins left.
//The player who take the coins with the most value wins.
//Could you please decide the first player will win or lose?
public boolean firstWillWin(int[] values) {
// write your code here
if(values.length < 3)
return true;
int len = values.length;
int[] dp = new int[len];
dp[len-1] = values[len-1];
dp[len-2] = values[len-1] + values[len-2];
for(int i=len-3; i>=0; i--){
dp[i] = Math.max(values[i] - dp[i+1], values[i] + values[i+1] - dp[i+2]);
}
return dp[0] > 0;
}
//There are n coins in a line. Two players take turns to take a coin from one of the ends of the line
//until there are no more coins left. The player with the larger amount of money wins.
//Could you please decide the first player will win or lose?
//Recursion
public boolean firstWillWin(int[] values) {
// write your code here
int len = values.length;
if(len < 2)
return true;
int res = helper(values, 0, len-1);
return res > 0;
}
public int helper(int[] values, int s, int e){
if(s==e)
return values[s];
return Math.max(values[s] - helper(values, s+1,e), values[e] - helper(values, s , e-1));
}
//DP
public boolean firstWillWin(int[] values) {
// write your code here
int len = values.length;
int[][] dp = new int[len][len];
dp[len-1][len-1] = values[len-1];
for(int i=len-2; i>=0; i--){
dp[i][i] = values[i];
for(int j = i+1; j
0;
}