Topic
Give you a rope of length n, please cut the rope into M segment (m and n are integers, n>1 and m>1) the length of each piece of rope is recorded as k[0],k[1],..., k[m]. What is the maximum possible product of k[0]k[1] ... *k[m]? For example, when the length of the rope is 8 o'clock, we cut it to a length of three 2,3,3, the maximum product is 18.
Thinking of solving problems
Dynamic programming (specific solutions and ideas see code comments)
Problem solving code (Python implementation)
# title One: give you a rope of length n, please cut the rope into M segment (m and n are integers, n>1 and m>1The length of each piece of rope is recorded as k[0],k[1],..., k[m].# excuse me k[0]*k[1]*...*K[m] What is the maximum possible product? # For example, when the length of the rope is 8 o'clock, we cut it to a length of 2,3, 3 of three, at this time the maximum product is the. #解题思路: Dynamic Programming def rope_cut (length): # optimal coefficient group, when length is 0 is 0, when length is 1 is 1, when the length is 2 is 2, when the length is greater than 3 o'clock, 3 can not cut, because 3 >1*2, the optimal coefficient group is 3 Li=[0,1,2,3] iflength==0: #当长度为0时, return 0return 0 iflength==1: #当长度为1时, return 1return 1 iflength==2: #当长度为2时, return 2return 2 iflength==3: #当长度为3时, return 2, although the optimal coefficient group is 2, but every time you have to cut a knife, so 1*2=2, so the length is 3 o'clock or 2.return 2 forJinchRange4, length+1): Max=0 forIinchRange1, J): # idea: Each time the value is solved, the other less than the length to be solved is listed to put in an array #如: The length is 5, the optimal coefficient group must have a length of 1,2,3, 4 of the optimal solution value #注: This is used to save the optimal coefficient group is for performance optimization, although recursive solution can also be solved, but will cause a large number of repeated execution temp=li[i]*li[j-i]ifTemp>Max:max=temp li.append (max) #每次将上次所得最优解追加在列表里returnli[-1]print (Rope_cut (8))
(PS: Just to say, the feeling of solving a problem is really good)
(python) sword refers to offer (second edition) face question 14: Cut the Rope