Skip to content

Commit 605399f

Browse files
authored
Merge branch 'youngyangyang04:master' into master
2 parents 9d92c13 + 9cbb439 commit 605399f

8 files changed

+241
-6
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/0151.翻转字符串里的单词.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,57 @@ class Solution {
318318

319319
Python:
320320

321+
```Python3
322+
class Solution:
323+
#1.去除多余的空格
324+
def trim_spaces(self,s):
325+
n=len(s)
326+
left=0
327+
right=n-1
328+
329+
while left<=right and s[left]==' ': #去除开头的空格
330+
left+=1
331+
while left<=right and s[right]==' ': #去除结尾的空格
332+
right=right-1
333+
tmp=[]
334+
while left<=right: #去除单词中间多余的空格
335+
if s[left]!=' ':
336+
tmp.append(s[left])
337+
elif tmp[-1]!=' ': #当前位置是空格,但是相邻的上一个位置不是空格,则该空格是合理的
338+
tmp.append(s[left])
339+
left+=1
340+
return tmp
341+
#2.翻转字符数组
342+
def reverse_string(self,nums,left,right):
343+
while left<right:
344+
nums[left], nums[right]=nums[right],nums[left]
345+
left+=1
346+
right-=1
347+
return None
348+
#3.翻转每个单词
349+
def reverse_each_word(self, nums):
350+
start=0
351+
end=0
352+
n=len(nums)
353+
while start<n:
354+
while end<n and nums[end]!=' ':
355+
end+=1
356+
self.reverse_string(nums,start,end-1)
357+
start=end+1
358+
end+=1
359+
return None
360+
361+
#4.翻转字符串里的单词
362+
def reverseWords(self, s): #测试用例:"the sky is blue"
363+
l = self.trim_spaces(s) #输出:['t', 'h', 'e', ' ', 's', 'k', 'y', ' ', 'i', 's', ' ', 'b', 'l', 'u', 'e'
364+
self.reverse_string( l, 0, len(l) - 1) #输出:['e', 'u', 'l', 'b', ' ', 's', 'i', ' ', 'y', 'k', 's', ' ', 'e', 'h', 't']
365+
self.reverse_each_word(l) #输出:['b', 'l', 'u', 'e', ' ', 'i', 's', ' ', 's', 'k', 'y', ' ', 't', 'h', 'e']
366+
return ''.join(l) #输出:blue is sky the
367+
368+
369+
'''
370+
371+
321372
Go:
322373
323374
```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/0541.反转字符串II.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ public:
103103

104104
Java:
105105
```Java
106+
//解法一
106107
class Solution {
107108
public String reverseStr(String s, int k) {
108109
StringBuffer res = new StringBuffer();
@@ -128,6 +129,28 @@ class Solution {
128129
return res.toString();
129130
}
130131
}
132+
133+
//解法二(似乎更容易理解点)
134+
//题目的意思其实概括为 每隔2k个反转前k个,尾数不够k个时候全部反转
135+
class Solution {
136+
public String reverseStr(String s, int k) {
137+
char[] ch = s.toCharArray();
138+
for(int i = 0; i < ch.length; i += 2 * k){
139+
int start = i;
140+
//这里是判断尾数够不够k个来取决end指针的位置
141+
int end = Math.min(ch.length - 1, start + k - 1);
142+
//用异或运算反转
143+
while(start < end){
144+
ch[start] ^= ch[end];
145+
ch[end] ^= ch[start];
146+
ch[start] ^= ch[end];
147+
start++;
148+
end--;
149+
}
150+
}
151+
return new String(ch);
152+
}
153+
}
131154
```
132155

133156
Python:

problems/0654.最大二叉树.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,42 @@ func findMax(nums []int) (index int){
311311
}
312312
```
313313
314+
JavaScript版本
315+
316+
```javascript
317+
/**
318+
* Definition for a binary tree node.
319+
* function TreeNode(val, left, right) {
320+
* this.val = (val===undefined ? 0 : val)
321+
* this.left = (left===undefined ? null : left)
322+
* this.right = (right===undefined ? null : right)
323+
* }
324+
*/
325+
/**
326+
* @param {number[]} nums
327+
* @return {TreeNode}
328+
*/
329+
var constructMaximumBinaryTree = function (nums) {
330+
const BuildTree = (arr, left, right) => {
331+
if (left > right)
332+
return null;
333+
let maxValue = -1;
334+
let maxIndex = -1;
335+
for (let i = left; i <= right; ++i) {
336+
if (arr[i] > maxValue) {
337+
maxValue = arr[i];
338+
maxIndex = i;
339+
}
340+
}
341+
let root = new TreeNode(maxValue);
342+
root.left = BuildTree(arr, left, maxIndex - 1);
343+
root.right = BuildTree(arr, maxIndex + 1, right);
344+
return root;
345+
}
346+
let root = BuildTree(nums, 0, nums.length - 1);
347+
return root;
348+
};
349+
```
314350

315351

316352

problems/背包理论基础01背包-2.md

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
<a href="https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ"><img src="https://img.shields.io/badge/知识星球-代码随想录-blue" alt=""></a>
66
</p>
77
<p align="center"><strong>欢迎大家<a href="https://mp.weixin.qq.com/s/tqCxrMEU-ajQumL1i8im9A">参与本项目</a>,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!</strong></p>
8+
89
# 动态规划:关于01背包问题,你该了解这些!(滚动数组)
910

1011
昨天[动态规划:关于01背包问题,你该了解这些!](https://mp.weixin.qq.com/s/FwIiPPmR18_AJO5eiidT6w)中是用二维dp数组来讲解01背包。
@@ -35,7 +36,7 @@
3536

3637
**其实可以发现如果把dp[i - 1]那一层拷贝到dp[i]上,表达式完全可以是:dp[i][j] = max(dp[i][j], dp[i][j - weight[i]] + value[i]);**
3738

38-
**于其把dp[i - 1]这一层拷贝到dp[i]上,不如只用一个一维数组了**,只用dp[j](一维数组,也可以理解是一个滚动数组)。
39+
**与其把dp[i - 1]这一层拷贝到dp[i]上,不如只用一个一维数组了**,只用dp[j](一维数组,也可以理解是一个滚动数组)。
3940

4041
这就是滚动数组的由来,需要满足的条件是上一层可以重复利用,直接拷贝到当前层。
4142

@@ -214,7 +215,7 @@ int main() {
214215
Java:
215216

216217
```java
217-
public static void main(String[] args) {
218+
public static void main(String[] args) {
218219
int[] weight = {1, 3, 4};
219220
int[] value = {15, 20, 30};
220221
int bagWight = 4;
@@ -242,7 +243,24 @@ Java:
242243

243244

244245
Python:
245-
246+
```python
247+
def test_1_wei_bag_problem():
248+
weight = [1, 3, 4]
249+
value = [15, 20, 30]
250+
bag_weight = 4
251+
# 初始化: 全为0
252+
dp = [0] * (bag_weight + 1)
253+
254+
# 先遍历物品, 再遍历背包容量
255+
for i in range(len(weight)):
256+
for j in range(bag_weight, weight[i] - 1, -1):
257+
# 递归公式
258+
dp[j] = max(dp[j], dp[j - weight[i]] + value[i])
259+
260+
print(dp)
261+
262+
test_1_wei_bag_problem()
263+
```
246264

247265
Go:
248266
```go

0 commit comments

Comments
 (0)