Skip to content

Commit

Permalink
Merge branch 'master' into patch-31
Browse files Browse the repository at this point in the history
  • Loading branch information
youngyangyang04 authored May 28, 2021
2 parents 14221a5 + cbc5f95 commit 7fe1c5c
Show file tree
Hide file tree
Showing 13 changed files with 328 additions and 49 deletions.
22 changes: 22 additions & 0 deletions problems/0046.全排列.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,28 @@ class Solution {

Python:
```python3
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = [] #存放符合条件结果的集合
path = [] #用来存放符合条件的结果
used = [] #用来存放已经用过的数字
def backtrack(nums,used):
if len(path) == len(nums):
return res.append(path[:]) #此时说明找到了一组
for i in range(0,len(nums)):
if nums[i] in used:
continue #used里已经收录的元素,直接跳过
path.append(nums[i])
used.append(nums[i])
backtrack(nums,used)
used.pop()
path.pop()
backtrack(nums,used)
return res
```

Python(优化,不用used数组):
```python3
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = [] #存放符合条件结果的集合
Expand Down
15 changes: 14 additions & 1 deletion problems/0055.跳跃游戏.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,20 @@ func canJUmp(nums []int) bool {
}
```


Javascript:
```Javascript
var canJump = function(nums) {
if(nums.length === 1) return true
let cover = 0
for(let i = 0; i <= cover; i++) {
cover = Math.max(cover, i + nums[i])
if(cover >= nums.length - 1) {
return true
}
}
return false
};
```


-----------------------
Expand Down
15 changes: 14 additions & 1 deletion problems/0078.子集.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,20 @@ class Solution {
```

Python:

```python3
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = []
path = []
def backtrack(nums,startIndex):
res.append(path[:]) #收集子集,要放在终止添加的上面,否则会漏掉自己
for i in range(startIndex,len(nums)): #当startIndex已经大于数组的长度了,就终止了,for循环本来也结束了,所以不需要终止条件
path.append(nums[i])
backtrack(nums,i+1) #递归
path.pop() #回溯
backtrack(nums,0)
return res
```

Go:
```Go
Expand Down
18 changes: 17 additions & 1 deletion problems/0090.子集II.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,23 @@ class Solution {
```

Python:

```python3
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
res = [] #存放符合条件结果的集合
path = [] #用来存放符合条件结果
def backtrack(nums,startIndex):
res.append(path[:])
for i in range(startIndex,len(nums)):
if i > startIndex and nums[i] == nums[i - 1]: #我们要对同一树层使用过的元素进行跳过
continue
path.append(nums[i])
backtrack(nums,i+1) #递归
path.pop() #回溯
nums = sorted(nums) #去重需要排序
backtrack(nums,0)
return res
```

Go:
```Go
Expand Down
28 changes: 11 additions & 17 deletions problems/0142.环形链表II.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,25 +234,19 @@ class Solution:
```

Go:
```func detectCycle(head *ListNode) *ListNode {
if head ==nil{
return head
}
slow:=head
fast:=head.Next
for fast!=nil&&fast.Next!=nil{
if fast==slow{
slow=head
fast=fast.Next
for fast!=slow {
fast=fast.Next
slow=slow.Next
```go
func detectCycle(head *ListNode) *ListNode {
slow, fast := head, head
for fast != nil && fast.Next != nil {
slow = slow.Next
fast = fast.Next.Next
if slow == fast {
for slow != head {
slow = slow.Next
head = head.Next
}
return slow
return head
}
fast=fast.Next.Next
slow=slow.Next
}
return nil
}
Expand Down
16 changes: 16 additions & 0 deletions problems/0150.逆波兰表达式求值.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,22 @@ var evalRPN = function(tokens) {
};
```

python3

```python
def evalRPN(tokens) -> int:
stack = list()
for i in range(len(tokens)):
if tokens[i] not in ["+", "-", "*", "/"]:
stack.append(tokens[i])
else:
tmp1 = stack.pop()
tmp2 = stack.pop()
res = eval(tmp2+tokens[i]+tmp1)
stack.append(str(int(res)))
return stack[-1]
```


-----------------------
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
Expand Down
44 changes: 44 additions & 0 deletions problems/0232.用栈实现队列.md
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,50 @@ class MyQueue {


Python:
```python
# 使用两个栈实现先进先出的队列
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack1 = list()
self.stack2 = list()

def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
# self.stack1用于接受元素
self.stack1.append(x)

def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
# self.stack2用于弹出元素,如果self.stack2为[],则将self.stack1中元素全部弹出给self.stack2
if self.stack2 == []:
while self.stack1:
tmp = self.stack1.pop()
self.stack2.append(tmp)
return self.stack2.pop()

def peek(self) -> int:
"""
Get the front element.
"""
if self.stack2 == []:
while self.stack1:
tmp = self.stack1.pop()
self.stack2.append(tmp)
return self.stack2[-1]

def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return self.stack1 == [] and self.stack2 == []
```


Go:
Expand Down
19 changes: 13 additions & 6 deletions problems/0343.整数拆分.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,6 @@ dp[i]的定义讲贯彻整个解题过程,下面哪一步想不懂了,就想

**那有同学问了,j怎么就不拆分呢?**

j是从1开始遍历,拆分j的情况,在遍历j的过程中其实都计算过了。

**那有同学问了,j怎么就不拆分呢?**

j是从1开始遍历,拆分j的情况,在遍历j的过程中其实都计算过了。那么从1遍历j,比较(i - j) * j和dp[i - j] * j 取最大的。递推公式:dp[i] = max(dp[i], max((i - j) * j, dp[i - j] * j));

也可以这么理解,j * (i - j) 是单纯的把整数拆分为两个数相乘,而j * dp[i - j]是拆分成两个以及两个以上的个数相乘。
Expand Down Expand Up @@ -213,8 +209,19 @@ class Solution {
```

Python:


```python
class Solution:
def integerBreak(self, n: int) -> int:
dp = [0] * (n + 1)
dp[2] = 1
for i in range(3, n + 1):
# 假设对正整数 i 拆分出的第一个正整数是 j(1 <= j < i),则有以下两种方案:
# 1) 将 i 拆分成 j 和 i−j 的和,且 i−j 不再拆分成多个正整数,此时的乘积是 j * (i-j)
# 2) 将 i 拆分成 j 和 i−j 的和,且 i−j 继续拆分成多个正整数,此时的乘积是 j * dp[i-j]
for j in range(1, i):
dp[i] = max(dp[i], max(j * (i - j), j * dp[i - j]))
return dp[n]
```
Go:


Expand Down
46 changes: 45 additions & 1 deletion problems/0404.左叶子之和.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,51 @@ class Solution:
```
Go:


JavaScript:
递归版本
```javascript
var sumOfLeftLeaves = function(root) {
//采用后序遍历 递归遍历
// 1. 确定递归函数参数
const nodesSum = function(node){
// 2. 确定终止条件
if(node===null){
return 0;
}
let leftValue = sumOfLeftLeaves(node.left);
let rightValue = sumOfLeftLeaves(node.right);
// 3. 单层递归逻辑
let midValue = 0;
if(node.left&&node.left.left===null&&node.left.right===null){
midValue = node.left.val;
}
let sum = midValue + leftValue + rightValue;
return sum;
}
return nodesSum(root);
};
```
迭代版本
```javascript
var sumOfLeftLeaves = function(root) {
//采用层序遍历
if(root===null){
return null;
}
let queue = [];
let sum = 0;
queue.push(root);
while(queue.length){
let node = queue.shift();
if(node.left!==null&&node.left.left===null&&node.left.right===null){
sum+=node.left.val;
}
node.left&&queue.push(node.left);
node.right&&queue.push(node.right);
}
return sum;
};
```



Expand Down
23 changes: 22 additions & 1 deletion problems/0491.递增子序列.md
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,28 @@ class Solution {


Python:

```python3
class Solution:
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
res = []
path = []
def backtrack(nums,startIndex):
repeat = [] #这里使用数组来进行去重操作
if len(path) >=2:
res.append(path[:]) #注意这里不要加return,要取树上的节点
for i in range(startIndex,len(nums)):
if nums[i] in repeat:
continue
if len(path) >= 1:
if nums[i] < path[-1]:
continue
repeat.append(nums[i]) #记录这个元素在本层用过了,本层后面不能再用了
path.append(nums[i])
backtrack(nums,i+1)
path.pop()
backtrack(nums,0)
return res
```

Go:

Expand Down
35 changes: 16 additions & 19 deletions problems/0541.反转字符串II.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,27 +106,24 @@ Java:
class Solution {
public String reverseStr(String s, int k) {
StringBuffer res = new StringBuffer();

for (int i = 0; i < s.length(); i += (2 * k)) {
int length = s.length();
int start = 0;
while (start < length) {
// 找到k处和2k处
StringBuffer temp = new StringBuffer();
// 剩余字符大于 k 个,每隔 2k 个字符的前 k 个字符进行反转
if (i + k <= s.length()) {
// 反转前 k 个字符
temp.append(s.substring(i, i + k));
res.append(temp.reverse());

// 反转完前 k 个字符之后,如果紧接着还有 k 个字符,则直接加入这 k 个字符
if (i + 2 * k <= s.length()) {
res.append(s.substring(i + k, i + 2 * k));
// 不足 k 个字符,则直接加入剩下所有字符
} else {
res.append(s.substring(i + k, s.length()));
}
continue;
}
// 剩余字符少于 k 个,则将剩余字符全部反转。
temp.append(s.substring(i, s.length()));
// 与length进行判断,如果大于length了,那就将其置为length
int firstK = (start + k > length) ? length : start + k;
int secondK = (start + (2 * k) > length) ? length : start + (2 * k);

//无论start所处位置,至少会反转一次
temp.append(s.substring(start, firstK));
res.append(temp.reverse());

// 如果firstK到secondK之间有元素,这些元素直接放入res里即可。
if (firstK < secondK) { //此时剩余长度一定大于k。
res.append(s.substring(firstK, secondK));
}
start += (2 * k);
}
return res.toString();
}
Expand Down
Loading

0 comments on commit 7fe1c5c

Please sign in to comment.