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

一、动态规划

时间复杂度O(n^2)

#include <iostream>
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 <iostream>
#include <cmath>
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;
}

猜你喜欢

转载自blog.csdn.net/qq_34793133/article/details/80787136