Update README

This commit is contained in:
halfrost
2021-11-05 21:21:21 +08:00
committed by halfrost
parent 7d3ba345f3
commit f09ea6cd09
25 changed files with 2507 additions and 2275 deletions

View File

@ -26,4 +26,4 @@ Your algorithm should have a linear runtime complexity. Could you implement it w
## 解题思路
- 题目要求不能使用辅助空间,并且时间复杂度只能是线性的。
- 题目为什么要强调有一个数字出现一次其他的出现两次我们想到了异或运算的性质任何一个数字异或它自己都等于0。也就是说如果我们从头到尾依次异或数组中的每一个数字那么最终的结果刚好是那个只出现次的数字,因为那些出现两次的数字全部在异或中抵消掉了。于是最终做法是从头到尾依次异或数组中的每一个数字,那么最终得到的结果就是两个只出现一次的数字的异或结果。因为其他数字都出现了两次,在异或中全部抵消掉了。**利用的性质是 x^x = 0**。
- 题目为什么要强调有一个数字出现一次其他的出现两次我们想到了异或运算的性质任何一个数字异或它自己都等于0。也就是说如果我们从头到尾依次异或数组中的每一个数字那么最终的结果刚好是那个只出现次的数字,因为那些出现两次的数字全部在异或中抵消掉了。于是最终做法是从头到尾依次异或数组中的每一个数字,那么最终得到的结果就是两个只出现一次的数字的异或结果。因为其他数字都出现了两次,在异或中全部抵消掉了。**利用的性质是 x^x = 0**。

View File

@ -1,4 +1,4 @@
# [301. Remove Invalid Parentheses](https://leetcode-cn.com/problems/remove-invalid-parentheses/)
# [301. Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/)
## 题目
@ -53,3 +53,79 @@ Return all the possible results. You may return the answer in any order.
- 得分小于0
- lmoves小于0
- rmoves小于0
## 代码
```go
package leetcode
var (
res []string
mp map[string]int
n int
length int
maxScore int
str string
)
func removeInvalidParentheses(s string) []string {
lmoves, rmoves, lcnt, rcnt := 0, 0, 0, 0
for _, v := range s {
if v == '(' {
lmoves++
lcnt++
} else if v == ')' {
if lmoves != 0 {
lmoves--
} else {
rmoves++
}
rcnt++
}
}
n = len(s)
length = n - lmoves - rmoves
res = []string{}
mp = make(map[string]int)
maxScore = min(lcnt, rcnt)
str = s
backtrace(0, "", lmoves, rmoves, 0)
return res
}
func backtrace(i int, cur string, lmoves int, rmoves int, score int) {
if lmoves < 0 || rmoves < 0 || score < 0 || score > maxScore {
return
}
if lmoves == 0 && rmoves == 0 {
if len(cur) == length {
if _, ok := mp[cur]; !ok {
res = append(res, cur)
mp[cur] = 1
}
return
}
}
if i == n {
return
}
if str[i] == '(' {
backtrace(i+1, cur+string('('), lmoves, rmoves, score+1)
backtrace(i+1, cur, lmoves-1, rmoves, score)
} else if str[i] == ')' {
backtrace(i+1, cur+string(')'), lmoves, rmoves, score-1)
backtrace(i+1, cur, lmoves, rmoves-1, score)
} else {
backtrace(i+1, cur+string(str[i]), lmoves, rmoves, score)
}
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
```