Cattle off net - cut the rope (dynamic / greed)

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.

Enter a description

Enter a number n, see the problem surface meaning. (2 <= n <= 60)

 

Code

# - * - Coding: UTF-. 8 - * - 
class Solution:
     DEF cutRope (Self, Number):
         # Write code here Wallpaper 
        IF Number == 2 :
             return . 1
         IF Number ==. 3 :
             return 2
         # find the law obtained, cut m segments. m is an even number is number // 2-1, for the odd number // = 2 m. 
        IF number% 2 == 0:
            m = number//2-1
        else:
            m = number 2 //
         # if number is divisible by m, then the product of m (number) / m multiplied. If not divisible by each time a = (number // m + 1 ) + 1, number minus a, until the number is less than a. 
        a float = B (Number) / m
        a = number//m
        result = 1
        if a==b:
            result = a**m
        else:
            while(number>(a+1)):
                result *= a+1
                number -= a+1
            result *= number
        return result

Advanced Code

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;

Greedy Solution: When n is 5 or greater, we cut as much as a length of rope 3; and when the remaining length of the rope 4, the two lengths of rope cut the rope 2. Why did you choose 2, 3 is the smallest sub-problems? Because comprising 2,3 to each question, if we have to cut it down, the product becomes small. Why choose a length of 3? Since the time when n≥5, 3 (n-3) ≥2 (n-2)
 
# -*- coding:utf-8 -*-
class Solution:
    def cutRope(self, number):
        # write code here
        #动态规划
        if number==2:
            return 1
        if number==3:
            return 2
        #当n>=4时,dp(n)=max(dp(i)*dp(n-i))

        dp = [0,1,2,3]
        for i in range(4,number+1):
            maxre = 0
            for j in range(1,i//2+1):
                maxre = dp[j]*dp[i-j] if maxre<dp[j]*dp[i-j] else maxre
            dp.append(maxre)
        return dp[number]

Guess you like

Origin www.cnblogs.com/ditingz/p/12298093.html