mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-05 00:25:22 +08:00
Update README
This commit is contained in:
@ -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**。
|
||||
|
@ -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
|
||||
}
|
||||
|
||||
```
|
Reference in New Issue
Block a user