算法97:成绩排名---动态规划

 思路:动态规划

代码:

i , j , total = 0,0,0
n = int(input())
dp = [1] * n
for i in range(1,n):
    dp[i] = 0
for i in range(2,n+1):
    for j in range(i-1,0,-1):
        dp[j] = (j+1) * (dp[j-1] + dp[j])
for j in range(0,n):
    total += dp[j]
print(total)

 

思路:

链接:https://www.nowcoder.com/questionTerminal/3e483fe3c0bb447bb17ffb3eeeca78ba
来源:牛客网

dp[i[[j] 代表 index 从 i 到 j (包含 i 和 j)中的最大值

所以:

dp[i][j] = max(dp[i][k] + dp[k+1][j],dp[i][k] * dp[k+1][j])for i <=k < j

代码:

nums = list(map(int,input().strip().split()))
 
dp = [[0]*len(nums) for i in range(len(nums))]
 
for i in range(len(dp)-1,-1,-1):
    for j in range(len(dp[0])):
        if i == j:
            dp[i][j] = nums[i]
        else:
            for k in range(i,j):
                dp[i][j] = max([dp[i][k] + dp[k+1][j],dp[i][k] * dp[k+1][j],dp[i][j]])
 
# print(dp)
print(dp[0][len(nums)-1])

 

posted on 2019-07-20 21:12  吱吱了了  阅读(380)  评论(0编辑  收藏  举报

导航