当前位置:网站首页>Sword finger offer 14- I. cut rope
Sword finger offer 14- I. cut rope
2022-06-29 23:39:00 【anieoo】
Original link : The finger of the sword Offer 14- I. Cut the rope

solution:
Dynamic programming :
State means :dp[i] The length is i The maximum value of the product after the rope is segmented
The length is i The rope of can be reduced to j and i - j Two paragraphs , This can be divided into two cases :
① i - j No further reduction , therefore dp[i] = max(dp[i], j * (i - j));
② i - j Continue to reduce , therefore dp[i] = max(dp[i], j * dp[i - j]);
So it is concluded that Transfer equation :
dp[i] = max(dp[i], j * max(dp[i - j], i - j));
class Solution {
public:
int cuttingRope(int n) {
if(n == 2) return 1;
if(n == 3) return 2;
vector<int> dp(n + 1); //dp[i] The length is i The maximum value of the product of each section after the rope is cut
for(int i = 1;i <= n;i++) {
for(int j = 1;j < i;j++) {
dp[i] = max(dp[i], j * max(dp[i - j], i - j)); // Transfer equation
}
}
return dp[n];
}
};greedy :
Reduce the length as much as possible to 3 The rope of .
class Solution {
public:
int cuttingRope(int n) {
if(n <= 3) return n - 1; // A special case
int res = 1;
while(n > 4) {
res *= 3;
n -= 3;
}
return res * n;
}
};
边栏推荐
- AI empowers new retail, the way to win "wisdom" lies in ecological thinking | selected excerpts from digital intelligence night talk live broadcast
- 云服务器的安全设置常识
- [leetcode] a number that appears only once [136]
- constexpr 函数
- How to solve the problem that the computer time is not automatically updated after proofreading
- Solr basic operation
- Remember the process of checking online MySQL deadlock. You should not only know curd, but also know the principle of locking
- xutils3传集合
- 股票开户安全吗?上海股票开户。
- 海外数字身份验证服务商ADVANCE.AI入选EqualOcean《2022品牌出海服务市场研究报告》
猜你喜欢

Procurement intelligence is about to break out, and the "3+2" system of Alipay helps enterprises build core competitive advantages

Paper writing tool: latex online website

Speech signal processing (II): phonation physiology, auditory physiology and auditory psychology

2022 PMP project management examination agile knowledge points (5)

收藏!这些提高程序员生产力的工具你用过吗?

Yunhe enmo Guoqiang, identifiez - le, saisissez - le, avant l'ébullition de la base de données nationale

这个简单的小功能,半年为我们产研团队省下213个小时

C指针进阶2-->函数指针数组 回调函数简化计算器代码,基于回调函数模拟实现qsort函数

matplotlib matplotlib中plt.hist()参数解释

constexpr 函数
随机推荐
Become the only key
正则表达式:字符(2)
Solr basic operation
基金的估值,费用,会计核算
Metaq cluster installation test
剑指 Offer 14- II. 剪绳子 II
自己收藏的一些网址
Wechat applet: (update) cloud development wechat group contacts
大学里遗憾的事,希望你无怨也无悔
MetaQ集群安裝測試
收藏!这些提高程序员生产力的工具你用过吗?
提供有效的绩效评估
【一起上水硕系列】Day 8
云和恩墨盖国强,识别它、抓住它,在国产数据库沸腾以前
Project 1 - buffer pool [cmu 15-445645] notes
C指针进阶1-->字符指针,数组指针,指针与数组传参,函数指针
Cacti最大监控数测试
Jetpack之Room的使用,结合Flow
二叉树的序列化 力扣 297. 二叉树的序列化与反序列化 652. 寻找重复的子树
matplotlib matplotlib可视化之柱状图plt.bar()