Merge branch 'youngyangyang04:master' into master

This commit is contained in:
花无缺
2023-03-29 20:18:31 +08:00
committed by GitHub
7 changed files with 92 additions and 0 deletions

View File

@ -444,6 +444,8 @@ public:
};
```
* 时间复杂度: O(n + m)
* 空间复杂度: O(m), 只需要保存字符串needle的前缀表
# 前缀表不减一C++实现
@ -540,6 +542,9 @@ public:
}
};
```
* 时间复杂度: O(n + m)
* 空间复杂度: O(m)
# 总结

View File

@ -114,6 +114,7 @@ void removeExtraSpaces(string& s) {
}
```
有的同学可能发现用erase来移除空格在leetcode上性能也还行。主要是以下几点
1. leetcode上的测试集里字符串的长度不够长如果足够长性能差距会非常明显。
@ -197,6 +198,9 @@ public:
};
```
* 时间复杂度: O(n)
* 空间复杂度: O(1) 或 O(n),取决于语言中字符串是否可变
## 其他语言版本

View File

@ -130,6 +130,9 @@ public:
};
```
* 时间复杂度: O(n)
* 空间复杂度: O(1)

View File

@ -73,6 +73,8 @@ public:
}
};
```
* 时间复杂度: O(n)
* 空间复杂度: O(1)
不过这种解法还有一个问题,就是 我们最终还是要判断 一个字符串s + s是否出现过 s 的过程大家可能直接用containsfind 之类的库函数。 却忽略了实现这些函数的时间复杂度暴力解法是m * n一般库函数实现为 O(m + n))。
@ -185,6 +187,8 @@ public:
}
};
```
* 时间复杂度: O(n)
* 空间复杂度: O(n)
前缀表不减一的C++代码实现:
@ -219,6 +223,8 @@ public:
}
};
```
* 时间复杂度: O(n)
* 空间复杂度: O(n)
## 其他语言版本

View File

@ -65,6 +65,9 @@ public:
};
```
* 时间复杂度: O(n)
* 空间复杂度: O(1)
@ -96,6 +99,9 @@ public:
};
```
* 时间复杂度: O(n)
* 空间复杂度: O(1)或O(n), 取决于使用的语言中字符串是否可以修改.
另一种思路的解法
@ -116,6 +122,9 @@ public:
};
```
* 时间复杂度: O(n)
* 空间复杂度: O(1)
## 其他语言版本

View File

@ -66,6 +66,9 @@ public:
}
};
```
* 时间复杂度: O(n)
* 空间复杂度O(1)
是不是发现这代码也太简单了,哈哈。
# 总结

View File

@ -286,8 +286,70 @@ class Solution {
}
```
**90.子集II**
```java
class Solution {
List<List<Integer>> reslut = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> subsetsWithDup(int[] nums) {
if(nums.length == 0){
reslut.add(path);
return reslut;
}
Arrays.sort(nums);
backtracking(nums,0);
return reslut;
}
public void backtracking(int[] nums,int startIndex){
reslut.add(new ArrayList<>(path));
if(startIndex >= nums.length)return;
HashSet<Integer> hashSet = new HashSet<>();
for(int i = startIndex; i < nums.length; i++){
if(hashSet.contains(nums[i])){
continue;
}
hashSet.add(nums[i]);
path.add(nums[i]);
backtracking(nums,i+1);
path.removeLast();
}
}
}
```
**40.组合总和II**
```java
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort( candidates );
if( candidates[0] > target ) return result;
backtracking(candidates,target,0,0);
return result;
}
public void backtracking(int[] candidates,int target,int sum,int startIndex){
if( sum > target )return;
if( sum == target ){
result.add( new ArrayList<>(path) );
}
HashSet<Integer> hashSet = new HashSet<>();
for( int i = startIndex; i < candidates.length; i++){
if( hashSet.contains(candidates[i]) ){
continue;
}
hashSet.add(candidates[i]);
path.add(candidates[i]);
sum += candidates[i];
backtracking(candidates,target,sum,i+1);
path.removeLast();
sum -= candidates[i];
}
}
}
```
Python
**90.子集II**