LeetCode每日一練 矩陣中的最長遞增路徑

2021-10-08 13:04:26 字數 1503 閱讀 6914

給定乙個整數矩陣,找出最長遞增路徑的長度。

對於每個單元格,你可以往上,下,左,右四個方向移動。你不能在對角線方向上移動或移動到邊界外(即不允許環繞)

輸入:

nums =[

[9,9,4],

[6,6,8],

[2,1,1]

] 輸出:4

輸入:nums =[

[3,4,5],

[3,2,6],

[2,2,1]

] 輸出:4

深度優先遍歷

# -*- coding:utf-8 -*-

from functools import lru_cache

class

solution

:def

longestincreasingpath

(self, nums)

: dirs=[[

0,1]

,[1,

0],[

0,-1

],[-

1,0]

] @lru_cache(

none

)def

dfs(row,col)

: count=

1for x,y in dirs:

newrow,newcol=row+x,col+y

if0<=newrow<

len(nums)

and0

<=newcol<

len(nums[0]

)and nums[row]

[col]

[newcol]

count =

max(count,dfs(newrow,newcol)+1

)return count

lip=

0for i in

range

(len

(nums)):

for j in

range

(len

(nums[0]

)): lip =

max(lip,dfs(i,j)

)return lip

c=[[9,9

,4],

[6,6

,8],

[2,1

,1]]

result = solution(

)print

(result.longestincreasingpath(c)

)

@lru_cache(none)

functools模組的lru_cache裝飾器,可以快取最多maxsize個函式的呼叫結果,從而提高程式的執行效率,適用於耗時的函式。

引數maxsize為最多快取的次數,如果為none,則無限制,設定為2n時,效能最佳。

lru_cache裝飾的函式會有cache_clear和cache_info兩個方法,分別用於清除快取和檢視快取資訊。

Leetcode 每日一練

最小棧 設計乙個支援 push pop top 操作,並能在常數時間內檢索到最小元素的棧。push x 將元素 x 推入棧中。pop 刪除棧頂的元素。top 獲取棧頂元素。getmin 檢索棧中的最小元素。示例 輸入 minstack push push push getmin pop top ge...

Leetcode 每日一練

leetcode 每日一練 擁有最多糖果的孩子 給你乙個陣列 candies 和乙個整數 extracandies 其中 candies i 代表第 i 個孩子擁有的糖果數目。對每乙個孩子,檢查是否存在一種方案,將額外的 extracandies 個糖果分配給孩子們之後,此孩子有 最多 的糖果。注意...

Leetcode 每日一練

猜數字 小a 和 小b 在玩猜數字。小b 每次從 1,2,3 中隨機選擇乙個,小a 每次也從 1,2,3 中選擇乙個猜。他們一共進行三次這個遊戲,請返回 小a 猜對了幾次?輸入的guess陣列為 小a 每次的猜測,answer陣列為 小b 每次的選擇。guess和answer的長度都等於3。示例 1...