검지offer 면접문제 14 밧줄 자르기(동적 기획과 탐욕 알고리즘)

10898 단어
#include
#include

using namespace std;

//    
int maxProductAfterCutting_soution(int length)
{
	if (length < 2)
		return 0;
	if (length == 2)
		return 1;
	if (length == 3)
		return 2;
	int* products = new int[length + 1];
	//      products      ,       4 ,f(5) = f(3)*f(2) = 2*3 ;
	products[0] = 0;
	products[1] = 1;
	products[2] = 2;
	products[3] = 3;
	int max = 0;
	for (int i = 4; i <= length; ++i)
	{
		max = 0;
		for (int j = 0; j <= i / 2; ++j)
		{
			int product = products[j] * products[i - j];
			if (max < product)
				max = product;
			products[i] = max;
		}
	}
	max = products[length];
	delete[] products;
	return max;
}

//    

int maxProductAfterCutting_soution2(int length)
{
	if (length < 2)
		return 0;
	if (length == 2)
		return 1;
	if (length == 3)
		return 2;

	int timesOfthree = length / 3;
	if (length - timesOfthree * 3 == 1)
		timesOfthree -= 1;
	int timesOftwo = (length - timesOfthree * 3) / 2;
	return (int)(pow(3, timesOfthree))*(int)(pow(2, timesOftwo));
	
}



int  main()
{
	int max1 = 0;
	int max2 = 0;
	max1 = maxProductAfterCutting_soution(50);
	max2 = maxProductAfterCutting_soution2(50);
	cout << max1 << " " << max2;
	cin.get();
	return 0;
}

코드에서 그룹 제품에 대한 초기 값을 주의해야 합니다.

좋은 웹페이지 즐겨찾기