Python, C++, JavaScript, SQL 및 TypeScript의 다양한 LeetCode 솔루션을 살펴보세요. 여러 프로그래밍 언어로 인터뷰 준비, 학습 및 코드 연습에 적합합니다. Github 레포 링크
주어진 xn
판자
문자와 문자열 목록 단어
, 반품 보드에 있는 모든 단어.
각 단어는 연속적으로 인접한 셀의 문자로 구성되어야 합니다. 인접한 셀 수평 또는 수직으로 이웃합니다. 같은 문자 셀은 단어에서 두 번 이상 사용할 수 없습니다.
예시 1:
입력: 보드 = [["o","a","a","n"],["e","t","a","e"],["i","h","k ","r"],["i","f","l","v"]], 단어 = ["맹세","완두콩","먹다","비"] 산출: ["먹다","맹세"]
예 2:
입력: 보드 = [["a","b"],["c","d"]], 단어 = ["abcb"] 산출: []
제약:
m == 보드 길이
n == 보드[i].길이
1 <= m, n <= 12
보드[i][j]
는 소문자 영어 글자입니다.1 <= 단어.길이 <= 3 * 10 4
1 <= 단어[i].길이 <= 10
단어[i]
소문자 영어 글자로 구성됩니다.- 모든 문자열은
단어
독특합니다.
목차
비녀장파이썬
# 시간 복잡도: O(M(4*3^(L-1))) # 공간 복잡도: O(n) from typing import List class 솔루션: def findWords(self, board: List[List[str]], words : List[str]) -> List[str]: WORDKEY = "$" trie = {} 단어의 단어: node = 단어의 글자: node = node.setdefault(letter, {}) node[WORDKEY] = 단어 행 번호 = len(보드) 열 번호 = len(보드[0]) 일치하는 단어 = [] def backtracking(행, 열, 부모): 글자 = 보드[행][열] currNode = 부모[글자] wordMatch = currNode. wordMatch: matchedWords.append(wordMatch)인 경우 pop(WORDKEY, False) 행 오프셋, 열 오프셋에 대한 board[행][열] = "#" [(-1, 0), (0, 1), (1, 0) , (0, -1)]: newRow, newCol = row + rowOffset, col + colOffset if ( newRow < 0 또는 newRow >= rowNum 또는 newCol < 0 또는 newCol >= colNum ): board[newRow][newCol이 아니면 계속 ] in currNode: 백트래킹 계속(newRow, newCol, currNode) board[row][col] = letter if not currNode: parent.pop(letter) for row in range(rowNum): for col in range(colNum): if board [행][열] in trie: backtracking(행, 열, trie) matchedWords 반환 # 시간 복잡도: O(n*3^l) # 공간 복잡도: O(m) 클래스 TrieNode: def __init__(self, char=" "): self.char = char self.children = {} self.isEnd = False 클래스 Trie: def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for c 단어에서: if c not in node.children: node.children[c] = TrieNode() node = node.children.get(c) node.isEnd = True def startsWith(self, prefix): node = self.root for 접두사 c: c가 node.children에 없으면 False를 반환합니다. node = node.children[c] True를 반환합니다. def removeChars(self, word): node = self.root childList = [] for c in word: childList.append( [노드, c]) 노드 = 노드.어린이[c] 부모, 자식에 대한 역순(자식 목록): 대상 = 부모.어린이[자식] 대상.어린이: 부모.어린이[자식] 클래스를 반환합니다. 솔루션: def findWords (자기, 보드: List[List[str]], 단어: List[str]) -> List[str]: def dfs(trieForWords: Trie, 노드: TrieNode, 그리드: List[List[str]], 행: int, col: int, result: List[str], word=""): if node.isEnd: result.append(word) node.isEnd = False trieForWords.removeChars(word) if 0 <= row < ROW and 0 <= col < COL: char = grid[row][col] child = node.children.get(char) child가 None이 아닌 경우: word += char grid[row][col] = None for dR, dC in [ (0, 1), (1, 0), (-1, 0), (0, -1)]: dfs(trieForWords, 자식, 그리드, 행 + dR, 열 + dC, 결과, 단어) 그리드[행 ][col] = char ROW = len(board) COL = len(board[0]) trieForWords = Trie() 결과 = [] 단어의 단어에 대해: trieForWords.insert(word) r의 범위에 대해: c in range(COL): dfs(trieForWords, trieForWords.root, board, r, c, result) 결과 반환 board = [["o", "a", "a", "n"], ["e" , "t", "a", "e"], ["i", "h", "k", "r"], ["i", "f", "l", "v"]] 단어 = ["맹세", "완두콩", "먹다", "비"] print(Solution().findWords(board, words))