Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
youngyangyang04 committed Jun 21, 2021
2 parents aa87376 + 9cbb439 commit 05e5577
Show file tree
Hide file tree
Showing 15 changed files with 472 additions and 14 deletions.
53 changes: 53 additions & 0 deletions problems/0037.解数独.md
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,59 @@ class Solution:
backtrack(board)
```

Python3:

```python3
class Solution:
def __init__(self) -> None:
self.board = []

def isValid(self, row: int, col: int, target: int) -> bool:
for idx in range(len(self.board)):
# 同列是否重复
if self.board[idx][col] == str(target):
return False
# 同行是否重复
if self.board[row][idx] == str(target):
return False
# 9宫格里是否重复
box_row, box_col = (row // 3) * 3 + idx // 3, (col // 3) * 3 + idx % 3
if self.board[box_row][box_col] == str(target):
return False
return True

def getPlace(self) -> List[int]:
for row in range(len(self.board)):
for col in range(len(self.board)):
if self.board[row][col] == ".":
return [row, col]
return [-1, -1]

def isSolved(self) -> bool:
row, col = self.getPlace() # 找个空位置

if row == -1 and col == -1: # 没有空位置,棋盘被填满的
return True

for i in range(1, 10):
if self.isValid(row, col, i): # 检查这个空位置放i,是否合适
self.board[row][col] = str(i) # 放i
if self.isSolved(): # 合适,立刻返回, 填下一个空位置。
return True
self.board[row][col] = "." # 不合适,回溯

return False # 空位置没法解决

def solveSudoku(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if board is None or len(board) == 0:
return
self.board = board
self.isSolved()
```

Go:

Javascript:
Expand Down
40 changes: 40 additions & 0 deletions problems/0093.复原IP地址.md
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,46 @@ class Solution(object):
return ans```
```

```python3
class Solution:
def __init__(self) -> None:
self.s = ""
self.res = []

def isVaild(self, s: str) -> bool:
if len(s) > 1 and s[0] == "0":
return False

if 0 <= int(s) <= 255:
return True

return False

def backTrack(self, path: List[str], start: int) -> None:
if start == len(self.s) and len(path) == 4:
self.res.append(".".join(path))
return

for end in range(start + 1, len(self.s) + 1):
# 剪枝
# 保证切割完,s没有剩余的字符。
if len(self.s) - end > 3 * (4 - len(path) - 1):
continue
if self.isVaild(self.s[start:end]):
# 在参数处,更新状态,实则创建一个新的变量
# 不会影响当前的状态,当前的path变量没有改变
# 因此递归完不用path.pop()
self.backTrack(path + [self.s[start:end]], end)

def restoreIpAddresses(self, s: str) -> List[str]:
# prune
if len(s) > 3 * 4:
return []
self.s = s
self.backTrack([], 0)
return self.res
```

JavaScript:

```js
Expand Down
14 changes: 14 additions & 0 deletions problems/0106.从中序与后序遍历序列构造二叉树.md
Original file line number Diff line number Diff line change
Expand Up @@ -775,6 +775,20 @@ var buildTree = function(inorder, postorder) {
};
```

从前序与中序遍历序列构造二叉树

```javascript
var buildTree = function(preorder, inorder) {
if(!preorder.length)
return null;
let root = new TreeNode(preorder[0]);
let mid = inorder.findIndex((number) => number === root.val);
root.left = buildTree(preorder.slice(1, mid + 1), inorder.slice(0, mid));
root.right = buildTree(preorder.slice(mid + 1, preorder.length), inorder.slice(mid + 1, inorder.length));
return root;
};
```

-----------------------
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
Expand Down
19 changes: 19 additions & 0 deletions problems/0134.加油站.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,25 @@ class Solution:
```

Go:
```go
func canCompleteCircuit(gas []int, cost []int) int {
curSum := 0
totalSum := 0
start := 0
for i := 0; i < len(gas); i++ {
curSum += gas[i] - cost[i]
totalSum += gas[i] - cost[i]
if curSum < 0 {
start = i+1
curSum = 0
}
}
if totalSum < 0 {
return -1
}
return start
}
```

Javascript:
```Javascript
Expand Down
51 changes: 51 additions & 0 deletions problems/0151.翻转字符串里的单词.md
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,57 @@ class Solution {
```


```Python3
class Solution:
#1.去除多余的空格
def trim_spaces(self,s):
n=len(s)
left=0
right=n-1

while left<=right and s[left]==' ': #去除开头的空格
left+=1
while left<=right and s[right]==' ': #去除结尾的空格
right=right-1
tmp=[]
while left<=right: #去除单词中间多余的空格
if s[left]!=' ':
tmp.append(s[left])
elif tmp[-1]!=' ': #当前位置是空格,但是相邻的上一个位置不是空格,则该空格是合理的
tmp.append(s[left])
left+=1
return tmp
#2.翻转字符数组
def reverse_string(self,nums,left,right):
while left<right:
nums[left], nums[right]=nums[right],nums[left]
left+=1
right-=1
return None
#3.翻转每个单词
def reverse_each_word(self, nums):
start=0
end=0
n=len(nums)
while start<n:
while end<n and nums[end]!=' ':
end+=1
self.reverse_string(nums,start,end-1)
start=end+1
end+=1
return None

#4.翻转字符串里的单词
def reverseWords(self, s): #测试用例:"the sky is blue"
l = self.trim_spaces(s) #输出:['t', 'h', 'e', ' ', 's', 'k', 'y', ' ', 'i', 's', ' ', 'b', 'l', 'u', 'e'
self.reverse_string( l, 0, len(l) - 1) #输出:['e', 'u', 'l', 'b', ' ', 's', 'i', ' ', 'y', 'k', 's', ' ', 'e', 'h', 't']
self.reverse_each_word(l) #输出:['b', 'l', 'u', 'e', ' ', 'i', 's', ' ', 's', 'k', 'y', ' ', 't', 'h', 'e']
return ''.join(l) #输出:blue is sky the


'''
Go:
```go
Expand Down
6 changes: 3 additions & 3 deletions problems/0209.长度最小的子数组.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ public:
};
```

时间复杂度:$O(n)$
时间复杂度:$O(n)$
空间复杂度:$O(1)$

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

## 相关题目推荐

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



Expand Down
48 changes: 48 additions & 0 deletions problems/0235.二叉搜索树的最近公共祖先.md
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,54 @@ class Solution:
else: return root
```
Go:
> BSL法

```go
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
//利用BSL的性质(前序遍历有序)
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root==nil{return nil}
if root.Val>p.Val&&root.Val>q.Val{//当前节点的值大于给定的值,则说明满足条件的在左边
return lowestCommonAncestor(root.Left,p,q)
}else if root.Val<p.Val&&root.Val<q.Val{//当前节点的值小于各点的值,则说明满足条件的在右边
return lowestCommonAncestor(root.Right,p,q)
}else {return root}//当前节点的值在给定值的中间(或者等于),即为最深的祖先
}
```
> 普通法
```go
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
//递归会将值层层返回
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
//终止条件
if root==nil||root.Val==p.Val||root.Val==q.Val{return root}//最后为空或者找到一个值时,就返回这个值
//后序遍历
findLeft:=lowestCommonAncestor(root.Left,p,q)
findRight:=lowestCommonAncestor(root.Right,p,q)
//处理单层逻辑
if findLeft!=nil&&findRight!=nil{return root}//说明在root节点的两边
if findLeft==nil{//左边没找到,就说明在右边找到了
return findRight
}else {return findLeft}
}
```




Expand Down
22 changes: 21 additions & 1 deletion problems/0435.无重叠区间.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,27 @@ class Solution:

Go:


Javascript:
```Javascript
var eraseOverlapIntervals = function(intervals) {
intervals.sort((a, b) => {
return a[1] - b[1]
})

let count = 1
let end = intervals[0][1]

for(let i = 1; i < intervals.length; i++) {
let interval = intervals[i]
if(interval[0] >= right) {
end = interval[1]
count += 1
}
}

return intervals.length - count
};
```


-----------------------
Expand Down
Loading

0 comments on commit 05e5577

Please sign in to comment.