【Codewars-Pyramid Slide Down】(下三角矩阵求最长路径)

来源:互联网 发布:javascript编程实战 编辑:程序博客网 时间:2024/04/29 21:19

在刷Codewars的时候,发现了其中有这道题,感觉大神的解法很巧妙,记录下来,希望自己以后需要的时候能快速找到吧。
【题目1】
大致就是需要找到下三角矩阵的一个最长路径吧。
【解法】
无非还是动态规划的方法,每个点只能走到该节点下方节点或者下方节点的右节点。
这里贴出大神的解法吧,自己的解法确实感觉不如别人的巧妙。

def longest_slide_down(p):    res = p.pop()#感觉这个pop操作很是精彩,虽然可能破坏了原来的数组    while p:        tmp = p.pop()        res = [tmp[i] + max(res[i],res[i+1])  for i in range(len(tmp))]     return res.pop()

【题目2】
寻找矩阵的最小路径。
【解法】
仿照上一个也采用pop的方法来处理矩阵。
然后采用滚动数组的方法来解决吧。

def getMin(self, mmap, n, m):#mmap为矩阵,n为行数,m为列数        tmp = mmap.pop(0)        res = [0]*len(tmp)        res[0] = tmp[0]        for i in range(1,len(tmp)):            res[i] = tmp[i]+res[i-1]        while mmap:            s = mmap.pop(0)            res[0] = res[0]+s[0]            for i in range(1,len(s)):                res[i] = s[i] + min(res[i],res[i-1])        return res[-1] 
0 0
原创粉丝点击