题目
给下面5根绳子,两两相连,cost = 值相加,求连城一根时的最小花费
input : [1,3,2,5,4]
output 33
思路
贪心算法,求每两根绳子的最小花费即可
代码
def mincost(l):
if len(l) == 0:
return 0
if len(l) == 1:
return l[0]
if len(l) == 2:
return l[0]+l[1]
l.sort()
dp = [0]*(len(l))
dp[0] = l[0]+l[1]
l.pop(0)
l.pop(0)
i = 1
while l is not None:
l.append(dp[i-1])
l.sort()
if len(l) == 1:
sum = 0
for i in dp:
sum += i
return sum
dp[i] = l[0] + l[1]
l.pop(0)
l.pop(0)
i +=1