当前位置:网站首页>LeetCode 2312. Sell Wood Blocks
LeetCode 2312. Sell Wood Blocks
2022-08-02 07:49:00 【HumbleFool】
LeetCode 2312. 卖木头块
暴力递归 TLE
const int N = 210;
typedef long long LL;
class Solution {
public:
int price[N][N] = {
0};
LL dfs(int n, int m)
{
if(n == 0 || m == 0)
return 0;
//The whole piece is not separated
LL p1 = price[n][m];
// 按行分
LL p2 = 0;
for(int i = 1; i < n; i ++)
{
LL up = dfs(i, m);
LL down = dfs(n - i, m);
p2 = max(p2, up + down);
}
// 按列分
LL p3 = 0;
for(int i = 1; i < m; i ++)
{
LL left = dfs(n, i);
LL right = dfs(n, m - i);
p3 = max(p3, left + right);
}
return max(p1, max(p2, p3));
}
long long sellingWood(int n, int m, vector<vector<int>>& prices) {
// A two-dimensional table stores prices
for(auto&& p : prices)
price[p[0]][p[1]] = p[2];
return dfs(n, m);
}
};
记忆化搜索 AC
const int N = 210;
typedef long long LL;
class Solution {
public:
int price[N][N] = {
0};
LL f[N][N];
LL dfs(int n, int m)
{
// 0行或者0列
if(n == 0 || m == 0)
return 0;
// 记忆化
if(f[n][m] != -1)
return f[n][m];
//The whole piece is not separated
LL p1 = price[n][m];
// 按行分
LL p2 = 0;
for(int i = 1; i < n; i ++)
{
LL up = dfs(i, m);
LL down = dfs(n - i, m);
p2 = max(p2, up + down);
}
// 按列分
LL p3 = 0;
for(int i = 1; i < m; i ++)
{
LL left = dfs(n, i);
LL right = dfs(n, m - i);
p3 = max(p3, left + right);
}
f[n][m] = max(p1, max(p2, p3));
return f[n][m];
}
long long sellingWood(int n, int m, vector<vector<int>>& prices) {
// 2D record price
for(auto&& p : prices)
price[p[0]][p[1]] = p[2];
memset(f, -1, sizeof f);
return dfs(n, m);
}
};
Elegant dynamic programming
const int N = 210;
typedef long long LL;
class Solution {
public:
LL f[N][N] = {
0}; //表示i行jThe maximum block size of the column
long long sellingWood(int n, int m, vector<vector<int>>& prices) {
// 初始化
for(auto&& p : prices)
f[p[0]][p[1]] = p[2];
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= m; j ++)
{
// 按行分割
for(int k = 1; k <= (i >> 1); k ++)
f[i][j] = max(f[i][j], f[k][j] + f[i - k][j]);
// 按列分割
for(int k = 1; k <= (j >> 1); k ++)
f[i][j] = max(f[i][j], f[i][k] + f[i][j - k]);
}
return f[n][m];
}
};
边栏推荐
猜你喜欢

MPLS的相关技术

论文《Deep Multifaceted Transformers for Multi-objective Ranking in Large-Scale E-commerce Recommender》

Analysis of GCC compiler technology

实例027:递归输出

Neo4j 中文开发者月刊 - 202207期

【CV】OpenVINO安装教程

【故障诊断分析】基于matlab FFT轴承故障诊断(包络谱)【含Matlab源码 2002期】

吃透Chisel语言.30.Chisel进阶之通信状态机(二)——FSMD:以Popcount为例

System.Security.SecurityException: 未找到源,但未能搜索某些或全部事件日志。不可 访问的日志: Security

Splunk Filed extraction 字段截取
随机推荐
实例029:反向输出
【CV】OpenVINO安装教程
(Part of it is not understood, and the notes are not completed) [Graph Theory] Difference Constraints
交换部分 VLAN
Find the largest n files
敏捷、DevOps和嵌入式系统测试
入门opencv,欢笑快乐每一天
【网络】IP、子网掩码
PWA 踩坑 - 第一次加载页面后无法获取CacheStorage某些资源
实例030:回文数
深度学习网络模型的改进与调整
【红队】ATT&CK - 创建或修改系统进程实现持久化(更新ing)
apt & apt-get命令
(2022牛客多校五)D-Birds in the tree(树形DP)
牛客编程题中——需要处理输入较大数的题目
初探形式化方法基本原理
View port number occupancy
雷达人体存在感应器方案,智能物联网感知技术,实时感应人体存在
SQL server 2014 怎么一次性导出多个查询结果?
埋点开发流程