JZ067剪绳子

思路

动归 贪心

class Solution {
public:
    int cutRope(int number) {
        if (number < 2)
        {
            return 0;
        }
        if (number == 2)
        {
            return 1;
        }
        if(number == 3)
        {
            return 2;
        }
        int * result = new int[number+1];
        result[0] = 0;
        result[1]= 1;
        result[2] = 2;
        result[3]= 3;
        int max_val = 0;
        for (int i =4;i<=number;++i) //从4计算到number 
        {
            max_val = 0;
            for(int j = 1;j<=i/2;++j) //后面一半是重复的
            {
                int current = result[j]*result[i-j];
                if(max_val<current)
                    max_val = current;
                result[i] = max_val;
            }
        }
        max_val = result[number]; //赋值之后将新申请的数组删除
        delete []result;
        return max_val;
    }
};

 

posted @ 2021-09-26 16:25  A-inspire  Views(44)  Comments(0Edit  收藏  举报