劍指offer--面試題14:剪繩子

#include <stdio.h>
#include<math.h>

// ====================動態規劃====================
int maxProductAfterCutting_solution1(int len)
{
    if(len < 2)
        return 0;
    if(len == 2)
        return 1;
    if(len == 3)
        return 2;

    int* A = new int[len + 1];
    A[0] = 0;
    A[1] = 1;
    A[2] = 2;
    A[3] = 3;

    int max ;
    for(int i = 4; i <= len; ++i)
        for(int j = 1,max = 0; j <= i / 2; ++j)
        {
            int result = A[j] * A[i - j];
            if(max < result)
                max = result;
            A[i] = max;
        }
    max = A[len];
    delete[] A;

    return max;
}

// ====================貪婪算法====================
int maxProductAfterCutting_solution2(long int length)
{
    if(length < 2)
        return 0;
    if(length == 2)
        return 1;
    if(length == 3)
        return 2;

    // 儘可能多地減去長度爲3的繩子段
    int timesOf3 = length / 3;

    // 當繩子最後剩下的長度爲4的時候,不能再剪去長度爲3的繩子段。
    // 此時更好的方法是把繩子剪成長度爲2的兩段,因爲2*2 > 3*1。
    if(length - timesOf3 * 3 == 1)
        timesOf3 -= 1;

    int timesOf2 = (length - timesOf3 * 3) / 2;

    return (long int) (pow(3, timesOf3)) * (long int) (pow(2, timesOf2));
}

int main()
{
	long int length;
    while(1)
	{
		printf("請輸入繩子的長度:");
		scanf("%d",&length);
		printf("動態規劃法-----各段繩子的最大乘積爲:%d\n",maxProductAfterCutting_solution1(length));
		printf("貪婪法-----各段繩子的最大乘積爲:%d\n",maxProductAfterCutting_solution2(length));
	}


    return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章