Skip to content

Commit

Permalink
Update
Browse files Browse the repository at this point in the history
  • Loading branch information
youngyangyang04 committed Oct 9, 2024
2 parents ba20624 + aab47d3 commit dbc93eb
Show file tree
Hide file tree
Showing 21 changed files with 753 additions and 10 deletions.
15 changes: 13 additions & 2 deletions problems/0053.最大子序和.md
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ class Solution:
return result

```
贪心法
```python
class Solution:
def maxSubArray(self, nums):
Expand All @@ -226,8 +227,18 @@ class Solution:
if count <= 0: # 相当于重置最大子序起始位置,因为遇到负数一定是拉低总和
count = 0
return result


```
动态规划
```python
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
dp = [0] * len(nums)
dp[0] = nums[0]
res = nums[0]
for i in range(1, len(nums)):
dp[i] = max(dp[i-1] + nums[i], nums[i])
res = max(res, dp[i])
return res
```
### Go
贪心法
Expand Down
10 changes: 10 additions & 0 deletions problems/0070.爬楼梯完全背包版本.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,16 @@ if __name__ == '__main__':

### Go:
```go
package main

import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)

func climbStairs(n int, m int) int {
dp := make([]int, n+1)
dp[0] = 1
Expand Down
32 changes: 30 additions & 2 deletions problems/0093.复原IP地址.md
Original file line number Diff line number Diff line change
Expand Up @@ -467,9 +467,37 @@ class Solution:
num = int(s[start:end+1])
return 0 <= num <= 255

回溯(版本三)



```python
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
result = []
self.backtracking(s, 0, [], result)
return result

def backtracking(self, s, startIndex, path, result):
if startIndex == len(s):
result.append('.'.join(path[:]))
return

for i in range(startIndex, min(startIndex+3, len(s))):
# 如果 i 往后遍历了,并且当前地址的第一个元素是 0 ,就直接退出
if i > startIndex and s[startIndex] == '0':
break
# 比如 s 长度为 5,当前遍历到 i = 3 这个元素
# 因为还没有执行任何操作,所以此时剩下的元素数量就是 5 - 3 = 2 ,即包括当前的 i 本身
# path 里面是当前包含的子串,所以有几个元素就表示储存了几个地址
# 所以 (4 - len(path)) * 3 表示当前路径至多能存放的元素个数
# 4 - len(path) 表示至少要存放的元素个数
if (4 - len(path)) * 3 < len(s) - i or 4 - len(path) > len(s) - i:
break
if i - startIndex == 2:
if not int(s[startIndex:i+1]) <= 255:
break
path.append(s[startIndex:i+1])
self.backtracking(s, i+1, path, result)
path.pop()
```

### Go
Expand Down
9 changes: 6 additions & 3 deletions problems/0110.平衡二叉树.md
Original file line number Diff line number Diff line change
Expand Up @@ -609,10 +609,13 @@ class Solution:
while stack:
node = stack.pop()
if node:
stack.append(node)
stack.append(node) #
stack.append(None)
if node.left: stack.append(node.left)
if node.right: stack.append(node.right)
# 采用数组进行迭代,先将右节点加入,保证左节点能够先出栈
if node.right: #
stack.append(node.right)
if node.left: #
stack.append(node.left)
else:
real_node = stack.pop()
left, right = height_map.get(real_node.left, 0), height_map.get(real_node.right, 0)
Expand Down
2 changes: 1 addition & 1 deletion problems/0134.加油站.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ i从0开始累加rest[i],和记为curSum,一旦curSum小于零,说明[0, i

如果 curSum<0 说明 区间和1 + 区间和2 < 0, 那么 假设从上图中的位置开始计数curSum不会小于0的话,就是 区间和2>0。

区间和1 + 区间和2 < 0 同时 区间和2>0,只能说明区间和1 < 0, 那么就会从假设的箭头初就开始从新选择其实位置了
区间和1 + 区间和2 < 0 同时 区间和2>0,只能说明区间和1 < 0, 那么就会从假设的箭头初就开始从新选择起始位置了


**那么局部最优:当前累加rest[i]的和curSum一旦小于0,起始位置至少要是i+1,因为从i之前开始一定不行。全局最优:找到可以跑一圈的起始位置**
Expand Down
38 changes: 38 additions & 0 deletions problems/0151.翻转字符串里的单词.md
Original file line number Diff line number Diff line change
Expand Up @@ -475,7 +475,45 @@ class Solution:
words = words[::-1] # 反转单词
return ' '.join(words) #列表转换成字符串
```
(版本四) 将字符串转换为列表后,使用双指针去除空格
```python
class Solution:
def single_reverse(self, s, start: int, end: int):
while start < end:
s[start], s[end] = s[end], s[start]
start += 1
end -= 1

def reverseWords(self, s: str) -> str:
result = ""
fast = 0
# 1. 首先将原字符串反转并且除掉空格, 并且加入到新的字符串当中
# 由于Python字符串的不可变性,因此只能转换为列表进行处理
s = list(s)
s.reverse()
while fast < len(s):
if s[fast] != " ":
if len(result) != 0:
result += " "
while s[fast] != " " and fast < len(s):
result += s[fast]
fast += 1
else:
fast += 1
# 2.其次将每个单词进行翻转操作
slow = 0
fast = 0
result = list(result)
while fast <= len(result):
if fast == len(result) or result[fast] == " ":
self.single_reverse(result, slow, fast - 1)
slow = fast + 1
fast += 1
else:
fast += 1

return "".join(result)
```
### Go:

版本一:
Expand Down
6 changes: 5 additions & 1 deletion problems/0236.二叉树的最近公共祖先.md
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,11 @@ impl Solution {
p: Option<Rc<RefCell<TreeNode>>>,
q: Option<Rc<RefCell<TreeNode>>>,
) -> Option<Rc<RefCell<TreeNode>>> {
if root == p || root == q || root.is_none() {
if root.is_none() {
return root;
}
if Rc::ptr_eq(root.as_ref().unwrap(), p.as_ref().unwrap())
|| Rc::ptr_eq(root.as_ref().unwrap(), q.as_ref().unwrap()) {
return root;
}
let left = Self::lowest_common_ancestor(
Expand Down
23 changes: 23 additions & 0 deletions problems/0300.最长上升子序列.md
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,29 @@ pub fn length_of_lis(nums: Vec<i32>) -> i32 {
}
```

### Cangjie:

```cangjie
func lengthOfLIS(nums: Array<Int64>): Int64 {
let n = nums.size
if (n <= 1) {
return n
}
let dp = Array(n, item: 1)
var res = 0
for (i in 1..n) {
for (j in 0..i) {
if (nums[i] > nums[j]) {
dp[i] = max(dp[i], dp[j] + 1)
}
}
res = max(dp[i], res)
}
return res
}
```


<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
Expand Down
23 changes: 23 additions & 0 deletions problems/0343.整数拆分.md
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,29 @@ class Solution {
}
}
```
贪心
```Java
class Solution {
public int integerBreak(int n) {
// with 贪心
// 通过数学原理拆出更多的3乘积越大,则
/**
@Param: an int, the integer we need to break.
@Return: an int, the maximum integer after breaking
@Method: Using math principle to solve this problem
@Time complexity: O(1)
**/
if(n == 2) return 1;
if(n == 3) return 2;
int result = 1;
while(n > 4) {
n-=3;
result *=3;
}
return result*n;
}
}
```

### Python
动态规划(版本一)
Expand Down
3 changes: 2 additions & 1 deletion problems/0459.重复的子字符串.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ KMP算法中next数组为什么遇到字符不匹配的时候可以找到上一
![](https://code-thinking-1253855093.file.myqcloud.com/pics/20240913110841.png)
这里有录友就想:如果字符串s 是有是有最小重复子串p组成,最长相等前后缀就不能更长一些? 例如这样:
这里有录友就想:如果字符串s 是由最小重复子串p组成,最长相等前后缀就不能更长一些? 例如这样:
![](https://code-thinking-1253855093.file.myqcloud.com/pics/20240913114348.png)
Expand Down Expand Up @@ -884,3 +884,4 @@ public int[] GetNext(string s)
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

51 changes: 51 additions & 0 deletions problems/0494.目标和.md
Original file line number Diff line number Diff line change
Expand Up @@ -706,6 +706,57 @@ class Solution:
```

### Go
二维dp
```go
func findTargetSumWays(nums []int, target int) int {
sum := 0
for _, v := range nums {
sum += v
}
if math.Abs(float64(target)) > float64(sum) {
return 0 // 此时没有方案
}
if (target + sum) % 2 == 1 {
return 0 // 此时没有方案
}
bagSize := (target + sum) / 2

dp := make([][]int, len(nums))
for i := range dp {
dp[i] = make([]int, bagSize + 1)
}

// 初始化最上行
if nums[0] <= bagSize {
dp[0][nums[0]] = 1
}

// 初始化最左列,最左列其他数值在递推公式中就完成了赋值
dp[0][0] = 1

var numZero float64
for i := range nums {
if nums[i] == 0 {
numZero++
}
dp[i][0] = int(math.Pow(2, numZero))
}

// 以下遍历顺序行列可以颠倒
for i := 1; i < len(nums); i++ { // 行,遍历物品
for j := 0; j <= bagSize; j++ { // 列,遍历背包
if nums[i] > j {
dp[i][j] = dp[i-1][j]
} else {
dp[i][j] = dp[i-1][j] + dp[i-1][j-nums[i]]
}
}
}
return dp[len(nums)-1][bagSize]
}
```

一维dp
```go
func findTargetSumWays(nums []int, target int) int {
sum := 0
Expand Down
24 changes: 24 additions & 0 deletions problems/0518.零钱兑换II.md
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,7 @@ class Solution:

### Go:

一维dp
```go
func change(amount int, coins []int) int {
// 定义dp数组
Expand All @@ -306,6 +307,29 @@ func change(amount int, coins []int) int {
return dp[amount]
}
```
二维dp
```go
func change(amount int, coins []int) int {
dp := make([][]int, len(coins))
for i := range dp {
dp[i] = make([]int, amount + 1)
dp[i][0] = 1
}
for j := coins[0]; j <= amount; j++ {
dp[0][j] += dp[0][j-coins[0]]
}
for i := 1; i < len(coins); i++ {
for j := 1; j <= amount; j++ {
if j < coins[i] {
dp[i][j] = dp[i-1][j]
} else {
dp[i][j] = dp[i][j-coins[i]] + dp[i-1][j]
}
}
}
return dp[len(coins)-1][amount]
}
```

### Rust:

Expand Down
19 changes: 19 additions & 0 deletions problems/0674.最长连续递增序列.md
Original file line number Diff line number Diff line change
Expand Up @@ -492,6 +492,25 @@ int findLengthOfLCIS(int* nums, int numsSize) {
}
```

### Cangjie

```cangjie
func findLengthOfLCIS(nums: Array<Int64>): Int64 {
let n = nums.size
if (n <= 1) {
return n
}
let dp = Array(n, repeat: 1)
var res = 0
for (i in 1..n) {
if (nums[i] > nums[i - 1]) {
dp[i] = dp[i - 1] + 1
}
res = max(res, dp[i])
}
return res
}
```



Expand Down
19 changes: 19 additions & 0 deletions problems/0718.最长重复子数组.md
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,25 @@ int findLength(int* nums1, int nums1Size, int* nums2, int nums2Size) {
}
```
### Cangjie
```cangjie
func findLength(nums1: Array<Int64>, nums2: Array<Int64>): Int64 {
let n = nums1.size
let m = nums2.size
let dp = Array(n + 1, {_ => Array(m + 1, item: 0)})
var res = 0
for (i in 1..=n) {
for (j in 1..=m) {
if (nums1[i - 1] == nums2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1
}
res = max(res, dp[i][j])
}
}
return res
}
```


<p align="center">
Expand Down
Loading

0 comments on commit dbc93eb

Please sign in to comment.