-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path14_CuttingRope_DP.cpp
More file actions
72 lines (55 loc) · 1.73 KB
/
14_CuttingRope_DP.cpp
File metadata and controls
72 lines (55 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//
// main.cpp
// pointer2offer
//
// Created by mark on 2019/7/3.
// Copyright © 2019年 mark. All rights reserved.
//
/*
说明:
1. 问题:14.剪绳子问题,把长度为n的绳子剪成m段,如何让每段绳子长度最大?
2. 思路:动态规划/贪心算法
1. 自上而下分解子问题:f(n) = max(f(i) * f(n));
2. 自下而上求解:分别求得f(1),f(2),...子问题的解,并用一个数组存储,供每次求更大n时调用;
3. 扩展:
*/
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
int maxProductAfterCuting(int length)
{
if(length < 2)
return 0;
if(length == 2)
return 1;
int* products = new int[length+1]; // 记录每个子问题(每段绳子)长度的乘积
products[0] = 0;
products[1] = 1;
products[2] = 2;
products[3] = 3; //绳长为3,一刀不剪最长为3
//products[4] = 4 // 绳长为4时,可列可不列,动态规划结果和不剪的值一样
int res;
for(int i = 4; i <= length; ++i)
{
int max = 0;
for(int j = 1; j <= i / 2; ++j) // 对i长度的每个子问题进行计算,找出i的子问题的最大值,存到对应products[i]里面,供之后使用
{
int product = products[j] * products[i-j];
if(max < product)
max = product;
products[i] = max;
}
}
res = products[length];
delete[] products;
return res;
}
int main(){
int length;
cout << "请输入绳子的长度:";
cin >> length;
int maxProduct = maxProductAfterCuting(length);
cout << maxProduct << endl;
return 0;
}