对动态规划进行降维打击 :: labuladong的算法小抄 #1055
Replies: 21 comments 9 replies
-
一脸懵逼的看完了。。。for (int j = i + 1; j < n; j++) {这里跟j=i+1初始条件没有任何关系。外层循环第一行定义一个变量,内层循环最后一行对这个变量赋值,这个变量就是i+1,j-1的值。循环条件是i--,j++ |
Beta Was this translation helpful? Give feedback.
-
看懂啦!谢谢东哥的空间压缩~! |
Beta Was this translation helpful? Give feedback.
-
东哥,请问自顶向下的DP如何对备忘录进行空间压缩呢? |
Beta Was this translation helpful? Give feedback.
-
@lhcezx 不好压缩,所以一般都是把自顶向下的递归解法改成自底向上的迭代算法,然后再压缩 |
Beta Was this translation helpful? Give feedback.
-
东哥你好,对于文中这一句如果计算状态 dp[i][j] 需要的都是 dp[i][j] 相邻的状态,那么就可以使用空间压缩技巧有点疑惑,能不能进行空间压缩只是看 class Solution {
public int lastStoneWeightII(int[] stones) {
if (stones.length == 1) {
return stones[0];
} else if (stones.length == 2) {
return Math.abs(stones[0] - stones[1]);
}
return dp(stones);
}
public int dp(int[] stones) {
int sum = 0;
for (int stone : stones) {
sum += stone;
}
int half = sum / 2;
int[][] dp = new int[stones.length + 1][half + 1];
Arrays.fill(dp[stones.length], 0);
for (int i = stones.length - 1; i >= 0; i--) {
for (int j = half; j >= 0; j--) {
int p1 = dp[i + 1][j];
int p2 = 0;
if (stones[i] <= j) {
p2 = stones[i] + dp[i + 1][j - stones[i]];
}
dp[i][j] = Math.max(p1, p2);
}
}
return sum - dp[0][half] * 2;
}
} 然后抽出主要逻辑: int p1 = dp[i + 1][j];
int p2 = 0;
if (stones[i] <= j) {
p2 = stones[i] + dp[i + 1][j - stones[i]];
}
dp[i][j] = Math.max(p1, p2); 我写到这里二维数组就停下了,因为我觉得 class Solution {
public int lastStoneWeightII(int[] stones) {
int sum = 0;
for (int i : stones) {
sum += i;
}
int target = sum >> 1;
//初始化dp数组
int[] dp = new int[target + 1];
for (int i = 0; i < stones.length; i++) {
//采用倒序
for (int j = target; j >= stones[i]; j--) {
//两种情况,要么放,要么不放
dp[j] = Math.max(dp[j], dp[j - stones[i]] + stones[i]);
}
}
return sum - 2 * dp[target];
}
}
|
Beta Was this translation helpful? Give feedback.
-
pre为啥在for循环里面初始化呢?那这样不就和i-1没关系了么? |
Beta Was this translation helpful? Give feedback.
-
感觉这一节有点烧脑,看了很久才模模糊糊知道流程是怎么在走,看懂了流程,但感觉还是很懵😱😱😱 |
Beta Was this translation helpful? Give feedback.
-
一维看不太懂呀,我就掌握二维的算了 |
Beta Was this translation helpful? Give feedback.
-
俄罗斯套娃信封问题也是空间压缩的一种吧? |
Beta Was this translation helpful? Give feedback.
-
过了一个月回来看这篇文章,还是没弄懂空间压缩😭 |
Beta Was this translation helpful? Give feedback.
-
我買書看到這章節也是不懂 主要是 這個例子 投影到一維 |
Beta Was this translation helpful? Give feedback.
-
新d[j] 需要 旧d[j]+新d[j-1]以及旧d[j-1]计算出来 新d[j+1] 需要 旧d[j+1]+新d[j]以及旧的d[j]计算出来 |
Beta Was this translation helpful? Give feedback.
-
打卡!降维的可读性真的好差2333,一刷先懂个大概!等二三刷来加强理解 |
Beta Was this translation helpful? Give feedback.
-
我觉得楼主对 temp=pre 这行代码解释的不够好,下面是我的解释,个人认为比楼主的解释好 然后在内层循环的最后一行,下一轮内层 j++ 循环之前,pre = temp; 这行代码 |
Beta Was this translation helpful? Give feedback.
-
这是来自QQ邮箱的假期自动回复邮件。
您好,我最近正在休假中,无法亲自回复您的邮件。我将在假期结束后,尽快给您回复。
|
Beta Was this translation helpful? Give feedback.
-
文章链接点这里:对动态规划进行降维打击
评论礼仪 见这里,违者直接拉黑。
Beta Was this translation helpful? Give feedback.
All reactions