Skip to content

Commit 05e5577

Browse files
2 parents aa87376 + 9cbb439 commit 05e5577

15 files changed

+472
-14
lines changed

problems/0037.解数独.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,59 @@ class Solution:
321321
backtrack(board)
322322
```
323323

324+
Python3:
325+
326+
```python3
327+
class Solution:
328+
def __init__(self) -> None:
329+
self.board = []
330+
331+
def isValid(self, row: int, col: int, target: int) -> bool:
332+
for idx in range(len(self.board)):
333+
# 同列是否重复
334+
if self.board[idx][col] == str(target):
335+
return False
336+
# 同行是否重复
337+
if self.board[row][idx] == str(target):
338+
return False
339+
# 9宫格里是否重复
340+
box_row, box_col = (row // 3) * 3 + idx // 3, (col // 3) * 3 + idx % 3
341+
if self.board[box_row][box_col] == str(target):
342+
return False
343+
return True
344+
345+
def getPlace(self) -> List[int]:
346+
for row in range(len(self.board)):
347+
for col in range(len(self.board)):
348+
if self.board[row][col] == ".":
349+
return [row, col]
350+
return [-1, -1]
351+
352+
def isSolved(self) -> bool:
353+
row, col = self.getPlace() # 找个空位置
354+
355+
if row == -1 and col == -1: # 没有空位置,棋盘被填满的
356+
return True
357+
358+
for i in range(1, 10):
359+
if self.isValid(row, col, i): # 检查这个空位置放i,是否合适
360+
self.board[row][col] = str(i) # 放i
361+
if self.isSolved(): # 合适,立刻返回, 填下一个空位置。
362+
return True
363+
self.board[row][col] = "." # 不合适,回溯
364+
365+
return False # 空位置没法解决
366+
367+
def solveSudoku(self, board: List[List[str]]) -> None:
368+
"""
369+
Do not return anything, modify board in-place instead.
370+
"""
371+
if board is None or len(board) == 0:
372+
return
373+
self.board = board
374+
self.isSolved()
375+
```
376+
324377
Go:
325378

326379
Javascript:

problems/0093.复原IP地址.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,46 @@ class Solution(object):
338338
return ans```
339339
```
340340

341+
```python3
342+
class Solution:
343+
def __init__(self) -> None:
344+
self.s = ""
345+
self.res = []
346+
347+
def isVaild(self, s: str) -> bool:
348+
if len(s) > 1 and s[0] == "0":
349+
return False
350+
351+
if 0 <= int(s) <= 255:
352+
return True
353+
354+
return False
355+
356+
def backTrack(self, path: List[str], start: int) -> None:
357+
if start == len(self.s) and len(path) == 4:
358+
self.res.append(".".join(path))
359+
return
360+
361+
for end in range(start + 1, len(self.s) + 1):
362+
# 剪枝
363+
# 保证切割完,s没有剩余的字符。
364+
if len(self.s) - end > 3 * (4 - len(path) - 1):
365+
continue
366+
if self.isVaild(self.s[start:end]):
367+
# 在参数处,更新状态,实则创建一个新的变量
368+
# 不会影响当前的状态,当前的path变量没有改变
369+
# 因此递归完不用path.pop()
370+
self.backTrack(path + [self.s[start:end]], end)
371+
372+
def restoreIpAddresses(self, s: str) -> List[str]:
373+
# prune
374+
if len(s) > 3 * 4:
375+
return []
376+
self.s = s
377+
self.backTrack([], 0)
378+
return self.res
379+
```
380+
341381
JavaScript:
342382

343383
```js

problems/0106.从中序与后序遍历序列构造二叉树.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -775,6 +775,20 @@ var buildTree = function(inorder, postorder) {
775775
};
776776
```
777777

778+
从前序与中序遍历序列构造二叉树
779+
780+
```javascript
781+
var buildTree = function(preorder, inorder) {
782+
if(!preorder.length)
783+
return null;
784+
let root = new TreeNode(preorder[0]);
785+
let mid = inorder.findIndex((number) => number === root.val);
786+
root.left = buildTree(preorder.slice(1, mid + 1), inorder.slice(0, mid));
787+
root.right = buildTree(preorder.slice(mid + 1, preorder.length), inorder.slice(mid + 1, inorder.length));
788+
return root;
789+
};
790+
```
791+
778792
-----------------------
779793
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
780794
* B站视频:[代码随想录](https://space.bilibili.com/525438321)

problems/0134.加油站.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,25 @@ class Solution:
240240
```
241241

242242
Go:
243+
```go
244+
func canCompleteCircuit(gas []int, cost []int) int {
245+
curSum := 0
246+
totalSum := 0
247+
start := 0
248+
for i := 0; i < len(gas); i++ {
249+
curSum += gas[i] - cost[i]
250+
totalSum += gas[i] - cost[i]
251+
if curSum < 0 {
252+
start = i+1
253+
curSum = 0
254+
}
255+
}
256+
if totalSum < 0 {
257+
return -1
258+
}
259+
return start
260+
}
261+
```
243262

244263
Javascript:
245264
```Javascript

problems/0151.翻转字符串里的单词.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,57 @@ class Solution {
301301
```
302302

303303

304+
```Python3
305+
class Solution:
306+
#1.去除多余的空格
307+
def trim_spaces(self,s):
308+
n=len(s)
309+
left=0
310+
right=n-1
311+
312+
while left<=right and s[left]==' ': #去除开头的空格
313+
left+=1
314+
while left<=right and s[right]==' ': #去除结尾的空格
315+
right=right-1
316+
tmp=[]
317+
while left<=right: #去除单词中间多余的空格
318+
if s[left]!=' ':
319+
tmp.append(s[left])
320+
elif tmp[-1]!=' ': #当前位置是空格,但是相邻的上一个位置不是空格,则该空格是合理的
321+
tmp.append(s[left])
322+
left+=1
323+
return tmp
324+
#2.翻转字符数组
325+
def reverse_string(self,nums,left,right):
326+
while left<right:
327+
nums[left], nums[right]=nums[right],nums[left]
328+
left+=1
329+
right-=1
330+
return None
331+
#3.翻转每个单词
332+
def reverse_each_word(self, nums):
333+
start=0
334+
end=0
335+
n=len(nums)
336+
while start<n:
337+
while end<n and nums[end]!=' ':
338+
end+=1
339+
self.reverse_string(nums,start,end-1)
340+
start=end+1
341+
end+=1
342+
return None
343+
344+
#4.翻转字符串里的单词
345+
def reverseWords(self, s): #测试用例:"the sky is blue"
346+
l = self.trim_spaces(s) #输出:['t', 'h', 'e', ' ', 's', 'k', 'y', ' ', 'i', 's', ' ', 'b', 'l', 'u', 'e'
347+
self.reverse_string( l, 0, len(l) - 1) #输出:['e', 'u', 'l', 'b', ' ', 's', 'i', ' ', 'y', 'k', 's', ' ', 'e', 'h', 't']
348+
self.reverse_each_word(l) #输出:['b', 'l', 'u', 'e', ' ', 'i', 's', ' ', 's', 'k', 'y', ' ', 't', 'h', 'e']
349+
return ''.join(l) #输出:blue is sky the
350+
351+
352+
'''
353+
354+
304355
Go:
305356
306357
```go

problems/0209.长度最小的子数组.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ public:
109109
};
110110
```
111111

112-
时间复杂度:$O(n)$
112+
时间复杂度:$O(n)$
113113
空间复杂度:$O(1)$
114114

115115
**一些录友会疑惑为什么时间复杂度是O(n)**
@@ -118,8 +118,8 @@ public:
118118

119119
## 相关题目推荐
120120

121-
* 904.水果成篮
122-
* 76.最小覆盖子串
121+
* [904.水果成篮](https://leetcode-cn.com/problems/fruit-into-baskets/)
122+
* [76.最小覆盖子串](https://leetcode-cn.com/problems/minimum-window-substring/)
123123

124124

125125

problems/0235.二叉搜索树的最近公共祖先.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,54 @@ class Solution:
265265
else: return root
266266
```
267267
Go:
268+
> BSL法
269+
270+
```go
271+
/**
272+
* Definition for a binary tree node.
273+
* type TreeNode struct {
274+
* Val int
275+
* Left *TreeNode
276+
* Right *TreeNode
277+
* }
278+
*/
279+
//利用BSL的性质(前序遍历有序)
280+
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
281+
if root==nil{return nil}
282+
if root.Val>p.Val&&root.Val>q.Val{//当前节点的值大于给定的值,则说明满足条件的在左边
283+
return lowestCommonAncestor(root.Left,p,q)
284+
}else if root.Val<p.Val&&root.Val<q.Val{//当前节点的值小于各点的值,则说明满足条件的在右边
285+
return lowestCommonAncestor(root.Right,p,q)
286+
}else {return root}//当前节点的值在给定值的中间(或者等于),即为最深的祖先
287+
}
288+
```
289+
290+
> 普通法
291+
292+
```go
293+
/**
294+
* Definition for a binary tree node.
295+
* type TreeNode struct {
296+
* Val int
297+
* Left *TreeNode
298+
* Right *TreeNode
299+
* }
300+
*/
301+
//递归会将值层层返回
302+
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
303+
//终止条件
304+
if root==nil||root.Val==p.Val||root.Val==q.Val{return root}//最后为空或者找到一个值时,就返回这个值
305+
//后序遍历
306+
findLeft:=lowestCommonAncestor(root.Left,p,q)
307+
findRight:=lowestCommonAncestor(root.Right,p,q)
308+
//处理单层逻辑
309+
if findLeft!=nil&&findRight!=nil{return root}//说明在root节点的两边
310+
if findLeft==nil{//左边没找到,就说明在右边找到了
311+
return findRight
312+
}else {return findLeft}
313+
}
314+
```
315+
268316

269317

270318

problems/0435.无重叠区间.md

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,27 @@ class Solution:
228228

229229
Go:
230230

231-
231+
Javascript:
232+
```Javascript
233+
var eraseOverlapIntervals = function(intervals) {
234+
intervals.sort((a, b) => {
235+
return a[1] - b[1]
236+
})
237+
238+
let count = 1
239+
let end = intervals[0][1]
240+
241+
for(let i = 1; i < intervals.length; i++) {
242+
let interval = intervals[i]
243+
if(interval[0] >= right) {
244+
end = interval[1]
245+
count += 1
246+
}
247+
}
248+
249+
return intervals.length - count
250+
};
251+
```
232252

233253

234254
-----------------------

0 commit comments

Comments
 (0)