2020-3-2 刷題記錄

前言:每天必須寫(xiě),多忙都得寫(xiě),如果我今年 12 月份之前沒(méi)做到 700 道,我會(huì)瞧不起我自己一輩子的

0X00 leetcode 刷題 7 道

0X01 每道題的小小總結(jié)

Reverse Linked List

熱身題, 這道題之前做過(guò),但是第一眼..看過(guò)去沒(méi)思路

其實(shí)就是兩個(gè)前向指針的問(wèn)題, 然后不斷的移動(dòng)

pre 記錄上一個(gè)節(jié)點(diǎn), cur 記錄當(dāng)前節(jié)點(diǎn),temp 記錄 cur.next 然后不斷移動(dòng)

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if head == None or head.next == None: return head

        pre, cur = None, head

        while cur:
            temp = cur.next
            cur.next = pre
            pre = cur
            cur = temp

        return pre

Surrounded Regions

一道 dfs 的題目, dfs 有一個(gè)確實(shí)能找到所有在一個(gè)集合里面的點(diǎn)

但是不能,讓這個(gè)集合的所有點(diǎn),都知道某個(gè)點(diǎn)碰到邊界的事情,所以要遍歷完所有集合的值以后,保存下來(lái),統(tǒng)一更新

class Solution:
    def solve(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        if len(board) == 0: return
        m, n = len(board), len(board[0])
        visited = [[False] * n for _  in range(m)]

        def dfs(x, y):
            if x < 0 or y < 0 or x >= m or y >= n:
                self.flip = False
                return
            if board[x][y] == "X" or visited[x][y]: return
            visited[x][y] = True
            self.collection.append((x, y))
            dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
            for dx, dy in dirs:
                dfs(x + dx, y + dy)

        for x in range(m):
            for y in range(n):
                if board[x][y] == "X" or visited[x][y]: continue
                self.flip = True
                self.collection = []
                dfs(x, y)
                if not self.flip: continue
                for x1, y1 in self.collection:
                    board[x1][y1] = "X"

Implement Trie (Prefix Tree)

今天主要做了 trie 樹(shù),這個(gè)題目做過(guò), 3.3 的時(shí)候好好總結(jié)一下 trie

class Trie:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = {}


    def insert(self, word: str) -> None:
        """
        Inserts a word into the trie.
        """
        p = self.root
        for c in word:
            if c not in p:
                p[c] = {}
            p = p[c]
        p['#'] = True


    def search(self, word: str) -> bool:
        """
        Returns if the word is in the trie.
        """
        node = self.find(word)
        return node is not None and '#' in node

    def find(self, prefix):
        p = self.root
        for c in prefix:
            if c not in p: return None
            p = p[c]
        return p
        

    def startsWith(self, prefix: str) -> bool:
        """
        Returns if there is any word in the trie that starts with the given prefix.
        """
        return self.find(prefix) is not None

Add and Search Word - Data structure design

trie 樹(shù)的典型應(yīng)用,不多說(shuō)了

class WordDictionary:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = {}

    def addWord(self, word: str) -> None:
        """
        Adds a word into the data structure.
        """
        p = self.root
        for c in word:
            if c not in p:
                p[c] = {}
            p = p[c]
        p['#'] = True


    def search(self, word: str) -> bool:
        """
        Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
        """
        
        def helper(root, start):
            p = root
            for i in range(start, len(word)):
                c = word[i]
                if c != '.':
                    if c not in p: return False
                    p = p[c]
                else:
                    for letter in string.ascii_letters:
                        if letter not in p: continue
                        if helper(p[letter], i + 1):
                            return True
                    
                    return False
            
            return '#' in p

        return helper(self.root, 0)

Word Search

這個(gè) dfs 的題目卡了我很久....還是 dfs 沒(méi)有總結(jié),這個(gè)代碼寫(xiě)得很亂,,,有時(shí)間得重做一下,,我用了一個(gè)回溯去做

但是看到下一題的大佬的代碼以后,知道自己寫(xiě)得就是一坨屎...

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        if len(board) == 0 or len(word) == 0: return False
        m, n = len(board), len(board[0])

        dirs = [(1, 0), (0, -1), (0, 1), (-1, 0)]
        
        def pos2idx(x, y):
            return x * n + y

        def dfs(x, y, idx):
            if idx == len(word): return True
            if x < 0 or y < 0 or x >= m or y >= n: return False
            if board[x][y] != word[idx]: return False

            idx1 = pos2idx(x, y)

            if idx1 in self.visited: return False

            self.visited.add(idx1)

            for dx, dy in dirs:
                if dfs(x+dx, y+dy, idx+1):
                    return True

            self.visited.remove(idx1)
            return False
            
            
        self.visited = set()

        for x in range(m):
            for y in range(n):
                if board[x][y] != word[0]: continue
                idx = pos2idx(x, y)
                self.visited.add(idx)
                for dx, dy in dirs:
                    if dfs(x+dx, y+dy, 1): return True
                self.visited.remove(idx)
                
        return False

好吧...我還是把代碼改回來(lái)了:

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        if len(board) == 0 or len(word) == 0: return False
        m, n = len(board), len(board[0])

        dirs = [(1, 0), (0, -1), (0, 1), (-1, 0)]

        def dfs(x, y, idx, visited):
            if idx == len(word): return True
            for dx, dy in dirs:
                x1, y1 = x + dx, y + dy
                if x1 < 0 or x1 >= m or y1 < 0 or y1 >= n: continue
                if (x1, y1) in visited: continue
                if board[x1][y1] !=  word[idx]: continue
                if dfs(x1, y1, idx + 1, {(x1, y1)} | visited): return True
            
            return False

        self.visited = set()

        for x in range(m):
            for y in range(n):
                if board[x][y] != word[0]: continue
                if dfs(x, y, 1, {(x, y)}): return True
                
        return False

這樣就好看多了..

Word Search II

trie 樹(shù)的經(jīng)典題,用 trie 樹(shù)加速 dfs 搜索

  • 根據(jù)輸入單詞建立一個(gè) trie
  • 將 trie 在 board 里用 dfs 去搜索

有兩個(gè)坑的地方:

  • 最后不得重復(fù)
  • 可能出現(xiàn)一個(gè)詞是另外一個(gè)詞的前綴,所以找到了這樣一個(gè)單詞以后,不能立即退出,還要繼續(xù)遍歷
class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        if len(board) == 0: return None
        m, n = len(board), len(board[0])
        dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]

        # 建立 trie 
        trie = {}
        for word in words:
            node = trie
            for char in word:
                node = node.setdefault(char, {})
            node['#'] = word

        def dfs(x, y, node, visited):
            if '#' in node: res.add(node['#'])
            for dx, dy in dirs:
                x1, y1 = x+dx, y+dy
                if  x1 < 0 or x1 >= m or y1 < 0 or y1 >= n: continue
                if (x1, y1) in visited: continue
                if board[x1][y1] not in node: continue
                dfs(x1, y1, node[board[x1][y1]], visited | {(x1, y1)})
        
        res = set()
        for x in range(m):
            for y in range(n):
                if board[x][y] not in trie: continue
                dfs(x, y, trie[board[x][y]], {(x, y)})
        
        return list(res)

Combination Sum IV

背包型動(dòng)態(tài)規(guī)劃,唉,懵逼了,沒(méi)想到轉(zhuǎn)移方程

看了答案才知道是一個(gè)完全背包問(wèn)題,背包問(wèn)題的動(dòng)態(tài)規(guī)劃我也沒(méi)總結(jié)....

class Solution:
    def combinationSum4(self, nums: List[int], target: int) -> int:
        # 完全背包問(wèn)題
        # 而且是 可重復(fù)使用, 且要注意順序
        # 轉(zhuǎn)移方程:
        # dp[x] = dp[x-nums[0]] + dp[x-nums[1]] + ... + dp[x-nums[-1]]
        # 一定是可重復(fù)使用且注意順序才能這么用
        if len(nums) == 0: return 0 
        dp = [0] * (target + 1)
        dp[0] = 1

        for i in range(1, target+1):
            for n in nums:
                if i < n: continue
                dp[i] += dp[i - n]
        
        return dp[target]
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市侦锯,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌意乓,老刑警劉巖票渠,帶你破解...
    沈念sama閱讀 218,858評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件颂鸿,死亡現(xiàn)場(chǎng)離奇詭異衬以,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)蚁趁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,372評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)裙盾,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人他嫡,你說(shuō)我怎么就攤上這事番官。” “怎么了钢属?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,282評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵徘熔,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我淆党,道長(zhǎng)酷师,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,842評(píng)論 1 295
  • 正文 為了忘掉前任染乌,我火速辦了婚禮山孔,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘荷憋。我一直安慰自己台颠,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,857評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布勒庄。 她就那樣靜靜地躺著串前,像睡著了一般。 火紅的嫁衣襯著肌膚如雪实蔽。 梳的紋絲不亂的頭發(fā)上荡碾,一...
    開(kāi)封第一講書(shū)人閱讀 51,679評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音局装,去河邊找鬼坛吁。 笑死,一個(gè)胖子當(dāng)著我的面吹牛铐尚,可吹牛的內(nèi)容都是我干的拨脉。 我是一名探鬼主播,決...
    沈念sama閱讀 40,406評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼塑径,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了填具?” 一聲冷哼從身側(cè)響起统舀,我...
    開(kāi)封第一講書(shū)人閱讀 39,311評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤匆骗,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后誉简,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體碉就,經(jīng)...
    沈念sama閱讀 45,767評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年闷串,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了瓮钥。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,090評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡烹吵,死狀恐怖碉熄,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情肋拔,我是刑警寧澤锈津,帶...
    沈念sama閱讀 35,785評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站凉蜂,受9級(jí)特大地震影響琼梆,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜窿吩,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,420評(píng)論 3 331
  • 文/蒙蒙 一茎杂、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧纫雁,春花似錦煌往、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,988評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至闲勺,卻和暖如春曾棕,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背菜循。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,101評(píng)論 1 271
  • 我被黑心中介騙來(lái)泰國(guó)打工翘地, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人癌幕。 一個(gè)月前我還...
    沈念sama閱讀 48,298評(píng)論 3 372
  • 正文 我出身青樓衙耕,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親勺远。 傳聞我的和親對(duì)象是個(gè)殘疾皇子橙喘,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,033評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容