剪绳子 算法_剑指offer面试题14----剪绳子(动态规划,贪心算法)

一、动态规划

时间复杂度O(n^2)

#include

using namespace std;

int maxProduct(int length)

{

if (length < 2)

return 0;

if (length == 2)//当绳子原长是2时候,因为必须要切,所以只能切成1和1

return 1;

if (length == 3)

return 2;

int* product = new int[length+1];//为什么加一,数组下标从0开始

memset(product, 0, length+1);

product[1] = 1;

product[2] = 2;//为什么不是上面的length==2时候的返回值1?之前的是总长度是2时候的子情况,

//而这里是当2作为切出的子长度时候,

//不切割了,保留2为好

product[3] = 3;

int Resultmax = 0;

for (int i = 4; i <= length; ++i)

{

int tempmax = 0;

for (int j = 1; j <= i/2;++j)

{

if (product[j] * product[i - j]>tempmax)

tempmax = (product[j] * product[i - j]);

}

product[i] = tempmax;

}

Resultmax = product[length];

delete[] product;

return Resultmax;

}

int main()

{

cout << maxProduct(8) << endl;

return 0;

}

二、贪心算法

设计思想:当length>=5时候,尽可能的剪出长度是3的子长度,当剩下的绳子长是4时候,剪出两个长位2的子绳、

最优解的正确性证明:当n>=5,3(n-3)>=2(n-2);当n=4时候,剪出一个3一个1不如两个2乘积大,两个2和一个4效果一样, 为什么剩4的时候还要剪?这是考虑当若一开始时候绳子原长length==4时候,至少要剪一刀

时间复杂度:O(1)

代码实现:

/**********************贪心算法**********************/

#include

#include

using namespace std;

int maxProduct(int length)

{

if (length < 2)

return 0;

if (length == 2)//当绳子原长是2时候,因为必须要切,所以只能切成1和1

return 1;

if (length == 3)

return 2;

int timesof3 = length / 3;

int timesof4 = 1;

if ((length-4)%3==0)

{

--timesof3; timesof4 = 1;

}

int ResultMax = pow(3, timesof3) * pow(2, timesof4);

return ResultMax;

}

int main()

{

cout << maxProduct(8) << endl;

return 0;

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值