标签:
定义:
考虑:
基于上述考虑,得到递归方程如下:
s c o r e [ i , j ] = s u m [ i ] − m i n ( s o c r e [ i + 1 , m a x ( j , 1 ) ] , . . . , s c o r e [ i + 2 ∗ j , m a x ( j , 2 ∗ j ) ] ) score[i, j] = sum[i] - min(socre[i + 1, max(j, 1)], ..., score[i + 2 * j, max(j, 2 * j)]) score[i,j]=sum[i]−min(socre[i+1,max(j,1)],...,score[i+2∗j,max(j,2∗j)])
进一步考虑,递归终止条件:
完整递归方程如下:
s c o r e [ i , j ] = { s u m [ i ] n − i < = 2 ∗ j T n − i > 2 ∗ j score[i, j] = \begin{cases} sum[i] & n - i <= 2 * j \\ T &n - i > 2 * j \end{cases} score[i,j]={sum[i]Tn−i<=2∗jn−i>2∗j
其 中 , T = s u m [ i ] − m i n ( s o c r e [ i + 1 , m a x ( j , 1 ) ] , . . . , s c o r e [ i + 2 ∗ j , m a x ( j , 2 ∗ j ) ] ) 其中,T = sum[i] - min(socre[i + 1, max(j, 1)], ..., score[i + 2 * j, max(j, 2 * j)]) 其中,T=sum[i]−min(socre[i+1,max(j,1)],...,score[i+2∗j,max(j,2∗j)])
回到题目
后缀和数组(suffix sum array)
当n = 8时,示例如下:
int stoneGameII(vector& nums) {
if(nums.empty())
return 0;
int n = nums.size();
for(int i = n - 2; i >= 0; --i)
nums[i] += nums[i + 1];
int m = n + 1 >> 1;
vector> dp(n, vector(m + 1, 0));
for(int i = n - 1; i >= 0; --i)
{
for(int j = 1; j <= m; ++j)
{
if(n - i <= j << 1)
{
dp[i][j] = nums[i];
continue;
}
int sm = nums[i];
for(int k = 1; k <= j << 1; ++k)
{
if(i + k >= n || k > m)
break;
if(dp[i + k][max(k, j)] < sm)
sm = dp[i + k][max(k, j)];
}
dp[i][j] = nums[i] - sm;
}
}
return dp[0][1];
}