本文主要是介绍2024.3.15力扣每日一题——卖木头块,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
2024.3.15
- 题目来源
- 我的题解
- 方法一 记忆化搜索(自顶向下)
- 方法二 动态规划(自底向上)
题目来源
力扣每日一题;题序:2312
我的题解
方法一 记忆化搜索(自顶向下)
用 f(x,y)表示当木块的高和宽分别是 x 和 y 时,可以得到的最多钱数。我们需要考虑三种情况:
- 如果数组 prices 中存在 (x,y,price) 这一三元组,那么可以将木块以 prices 的价格卖出。为了快速判断存在性,可以使用一个哈希映射来进行存储,即哈希映射的键为 ( h i h_i hi, w i w_i wi),值为 p r i c e i price_i pricei ,这样就可以根据木块的高和宽,在 O(1) 的时间得到对应的价格。这种情况的状态转移方程为:
f(x,y)=price。- 如果 x>1,那么可以沿水平方向将木块切成两部分,它们的高分别是 i ( 1 ≤ i < x ) i~(1 \leq i < x) i (1≤i<x)和 x−i,宽均为 y。因此可以得到状态转移方程:
f ( x , y ) = max 1 ≤ i < x { f ( i , y ) + f ( x − i , y ) } f(x, y) = \max_{1 \leq i < x} \big\{ f(i, y) + f(x-i, y) \big\} f(x,y)=max1≤i<x{f(i,y)+f(x−i,y)}- 如果 y>1,那么可以沿垂直方向将木块切成两部分,它们的宽分别是 j ( 1 ≤ j < y ) j~(1 \leq j < y) j (1≤j<y) 和 y−j,高均为 x。因此可以得到状态转移方程:
f ( x , y ) = max 1 ≤ j < y { f ( x , j ) + f ( x , y − j ) } f(x, y) = \max_{1 \leq j < y} \big\{ f(x, j) + f(x, y-j) \big\} f(x,y)=max1≤j<y{f(x,j)+f(x,y−j)}当有多种情况满足时,我们需要选择它们中的较大值。最终的答案即为 f(m,n)。
时间复杂度:O(mn(m+n)+p),其中 p 是数组 prices的长度。
空间复杂度:O(mn+p),即为哈希映射和动态规划的数组需要使用的空间。
public long sellingWood(int m, int n, int[][] prices) {Map<String, Integer> value = new HashMap<>();for (int[] price : prices) {value.put(price[0]+"-"+price[1], price[2]);}//记忆化搜索的备忘录long[][] memo = new long[m + 1][n + 1];for (long[] row : memo) {Arrays.fill(row, -1);}return dfs(m, n, value, memo);
}public long dfs(int x, int y, Map<String, Integer> value, long[][] memo) {if (memo[x][y] != -1) {return memo[x][y];}String key = x+"-"+y;long ret = value.containsKey(key) ? value.get(key) : 0;if (x > 1) {//沿水平方向切for (int i = 1; i < x; i++) {ret = Math.max(ret, dfs(i, y, value, memo) + dfs(x - i, y, value, memo));}}if (y > 1) {//沿垂直方向切for (int j = 1; j < y; j++) {ret = Math.max(ret, dfs(x, j, value, memo) + dfs(x, y - j, value, memo));}}memo[x][y] = ret;return ret;
}
方法二 动态规划(自底向上)
时间复杂度:O( m 2 + n 2 + p m^2+n^2+p m2+n2+p)
空间复杂度:O(mn+p)
public long sellingWood(int m, int n, int[][] prices) {Map<String, Integer> value = new HashMap<>();for (int[] price : prices) {value.put(price[0] + "-" + price[1], price[2]);}long[][] dp = new long[m + 1][n + 1];for (int x = 1; x <= m; x++) {for (int y = 1; y <= n; y++) {String key = x + "-" + y;long ret = value.containsKey(key) ? value.get(key) : 0;if (x > 1) {// 沿水平方向切for (int i = 1; i < x; i++) {ret = Math.max(ret, dp[i][y] + dp[x - i][y]);}}if (y > 1) {// 沿垂直方向切for (int j = 1; j < y; j++) {ret = Math.max(ret, dp[x][j] + dp[x][y - j]);}}dp[x][y] = ret;}}return dp[m][n];
}
有任何问题,欢迎评论区交流,欢迎评论区提供其它解题思路(代码),也可以点个赞支持一下作者哈😄~
这篇关于2024.3.15力扣每日一题——卖木头块的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!