leetcode专题刷题记录II——BFS / DFS / TOPO + 回溯

10 正则表达式

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        len_p = len(p)
        len_s = len(s)
        if len_p == 0:
            return len_s == 0
        
        # 根据*分类处理
        if len_p > 1 and p[1] == '*':
            
            # 假设p[0]在s[0]中匹配0个
            if self.isMatch(s, p[2:]):
                return True

            # s[0]和p[0]匹配上了,也就是p[0]在s[0]中大于或等于1个
            if len_s > 0 and (s[0] == p[0] or p[0] == '.'):
                return self.isMatch(s[1:], p)
            
            return False
        else:
            # s[0]和p[0]匹配,递归下一组
            if len_s > 0 and (s[0] == p[0] or p[0] == '.'):
                return self.isMatch(s[1:], p[1:])
            
            return False

17 电话号码的字母组合

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits: return []
        phone = ['abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']
        queue = ['']  # 初始化队列
        for digit in digits:
            for _ in range(len(queue)):
                tmp = queue.pop(0)
                for letter in phone[ord(digit) - 50]:
                    queue.append(tmp + letter)
        return queue

22 括号生成

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        ans = []
        # 根据n初始化可以使用的左括号和右括号数
        # open代表可以使用的左括号数,close代表可以使用的右括号数
        def dfs(s, open, close, res):
            # 如果可以使用的右括号数小于左括号数,说明这种搭配错误,停止分裂
            if close < open:
                return
            
            # 如果左括号用完了,直接把剩下的右括号加上,加入返回数组
            if open == 0:
                tmp = close * ')'
                s += tmp
                res.append(s)
            else:
                # 下一步分出两种选择,左括号和右括号,对应的左右括号数变化
                dfs(s + '(', open - 1, close, res)
                dfs(s + ')', open, close - 1,  res)
        
        dfs('', n, n, ans)
        return ans

37 解数独

class Solution:
    def solveSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: void Do not return anything, modify board in-place instead.
        """
        def check(x, y, s):
            # 行列是否冲突
            for i in range(9):
                if board[i][y] == s or board[x][i] == s:
                    return False
            # box是否冲突
            for i in [0, 1, 2]:
                for j in [0, 1, 2]:
                    if board[x//3*3+i][y//3*3+j] == s:
                        return False
            return True
        
        def bt(cur):
            if cur == 81:
                return True
            x, y = cur // 9, cur % 9
            if board[x][y] != '.':
                return bt(cur + 1)
            for i in range(1, 10):
                s = str(i)
                if check(x, y, s):
                    # 设置该值
                    board[x][y] = s
                    # 进行递归检查冲突
                    if bt(cur + 1):
                        return True
                    # 填充失败,回溯
                    board[x][y] = '.'
            return False
        
        bt(0)

39 组合总和

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        candidates = sorted(candidates)
        res = []
        len_list = len(candidates)
        
        def helper(target, path, start):
            nonlocal res
            nonlocal candidates
            nonlocal len_list

            if target == 0:
                res.append(path.copy())
            
            for i in range(start, len_list):
                if target -  candidates[i] < 0:
                    break
                
                path.append(candidates[i])
                helper(target - candidates[i], path, i)
                path.pop()
        
        helper(target, [], 0)
        return res

40 组合总和II

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        candidates = sorted(candidates)
        res = []
        len_list = len(candidates)
        
        def helper(target, path, start):
            nonlocal res
            nonlocal candidates
            nonlocal len_list

            if target == 0:
                res.append(path.copy())
            
            for i in range(start, len_list):
                if target -  candidates[i] < 0:
                    break

                # 去重
                if i > start and candidates[i] == candidates[i-1]:
                    continue
                
                path.append(candidates[i])
                # 和I的区别就在于1.需要去重2.不包含自己
                helper(target - candidates[i], path, i + 1)
                path.pop()
        
        helper(target, [], 0)
        return res

44 通配符匹配

class Solution:
    def isMatch(self, s: str, p: 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值