Wins the offer of cut the rope

Title Description

You give a string of length n, please cut the rope segment length integer m (m, n are integers, n> 1 and m> 1), the length of each rope is referred to as k [0], k [1], ..., k [m]. Will k [0] xk [1] x ... xk [m] maximum possible product is how much? For example, when the length of the rope is 8:00, we cut it into lengths of three sections 2,3,3 of the product obtained at this time is the maximum 18.

Thinking

Features four dynamic programming problem solving:
① the optimal solution of a problem;
optimal solution to the overall problem ② is dependent on the respective sub-optimal solution;
between the problems ③ there is little overlap of the smaller sub-problem;
④ down from the analysis of the problem, to solve the problem from the bottom up;

Specific to this question, when the number <4, the maximum cutting is not cut, when the number> 4, there must be a point of consideration of the rope is divided into two, the maximum value of each product derived from two divided composition the entire product of the maximum rope. Why will not the rope is divided into 3 parts, 4 parts, because these solutions are in fact covered by the 2 parts inside.

Code

class Solution {
public:
    int cutRope(int number) {
        if(number < 1)
            return 0;
        vector<int> res(number+1);
        if(number==2)
            return 1;
        if(number==3)
            return 2;
        
        res[1] = 1;
        res[2] = 2;
        res[3] = 3;
        
        int tmp = 0;
        
        for(int i =4 ; i <=number ; i++)
        {
            for(int j = 1; j <= i/2;j++)
            {
                tmp = max(tmp, res[j]*res[i-j]);
            }
            res[i] = tmp;
        }
        return res[number];
    }
};
Published 85 original articles · won praise 0 · Views 388

Guess you like

Origin blog.csdn.net/weixin_38312163/article/details/104888963