mirror of
https://github.com/CyC2018/Interview-Notebook.git
synced 2026-10-30 07:33:45 +00:00
Update 14. 剪绳子.md
题目链接改为力扣中的对应题目,题目描述和代码按该题的接口调整。
This commit is contained in:
+12
-12
@@ -2,7 +2,7 @@
|
||||
|
||||
## 题目链接
|
||||
|
||||
[牛客网](https://www.nowcoder.com/practice/57d85990ba5b440ab888fc72b0751bf8?tpId=13&tqId=33257&tab=answerKey&from=cyc_github)
|
||||
[Leetcode](https://leetcode.cn/problems/jian-sheng-zi-lcof/)
|
||||
|
||||
## 题目描述
|
||||
|
||||
@@ -37,17 +37,17 @@ return 36 (10 = 3 + 3 + 4)
|
||||
继续拆成更大的绳子可以发现都比拆成 2 和 3 的效果更差,因此我们只考虑将绳子拆成 2 和 3,并且优先拆成 3,当拆到绳子长度 n 等于 4 时,也就是出现 3+1,此时只能拆成 2+2。
|
||||
|
||||
```java
|
||||
public int cutRope(int n) {
|
||||
if (n < 2)
|
||||
public int cuttingBamboo(int bamboo_len) {
|
||||
if (bamboo_len < 2)
|
||||
return 0;
|
||||
if (n == 2)
|
||||
if (bamboo_len == 2)
|
||||
return 1;
|
||||
if (n == 3)
|
||||
if (bamboo_len == 3)
|
||||
return 2;
|
||||
int timesOf3 = n / 3;
|
||||
if (n - timesOf3 * 3 == 1)
|
||||
int timesOf3 = bamboo_len / 3;
|
||||
if (bamboo_len - timesOf3 * 3 == 1)
|
||||
timesOf3--;
|
||||
int timesOf2 = (n - timesOf3 * 3) / 2;
|
||||
int timesOf2 = (bamboo_len - timesOf3 * 3) / 2;
|
||||
return (int) (Math.pow(3, timesOf3)) * (int) (Math.pow(2, timesOf2));
|
||||
}
|
||||
```
|
||||
@@ -55,13 +55,13 @@ public int cutRope(int n) {
|
||||
### 动态规划
|
||||
|
||||
```java
|
||||
public int cutRope(int n) {
|
||||
int[] dp = new int[n + 1];
|
||||
public int cuttingBamboo(int bamboo_len) {
|
||||
int[] dp = new int[bamboo_len + 1];
|
||||
dp[1] = 1;
|
||||
for (int i = 2; i <= n; i++)
|
||||
for (int i = 2; i <= bamboo_len; i++)
|
||||
for (int j = 1; j < i; j++)
|
||||
dp[i] = Math.max(dp[i], Math.max(j * (i - j), dp[j] * (i - j)));
|
||||
return dp[n];
|
||||
return dp[bamboo_len];
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Reference in New Issue
Block a user