当前位置:网站首页>Leetcode backtracking method
Leetcode backtracking method
2022-07-05 06:13:00 【Dawnlighttt】
List of articles
q22 Bracket generation
Answer key
Let's solve this problem in a different way , The topic requires to use n Arrange brackets , We are from 2 * n Choose between the brackets to arrange them from left to right . At this time, we found out , We have chosen more left parentheses than right parentheses , such as "((("、"(()"、"(())“ Such a situation is allowed , however ”())" Such a situation cannot happen . So we made such a strategy at the beginning :
- As long as the left bracket always has , Then you can always choose the left bracket
- As long as the number of left parentheses is greater than the number of right parentheses , We can choose the right bracket
- When the number of parentheses equals 2 * n, Indicates that an arrangement has been obtained
func generateParenthesis(n int) []string {
res := []string{
}
var dfs func(lBracket int, rBracket int, path string)
dfs = func(lBracket int, rBracket int, path string){
if len(path) >= 2 * n {
res = append(res, path)
return
}
if lBracket > 0 {
dfs(lBracket - 1, rBracket, path + "(")
}
if rBracket > lBracket {
dfs(lBracket, rBracket - 1, path + ")")
}
}
dfs(n, n, "")
return res
}
q40 Combinatorial summation 2
Answer key
This problem uses dfs To solve , First, clarify the situation of reaching the leaf node , Is that when target Be reduced to 0 When , Then go through candidates The subscript , To create a new branch , And subscript as dfs Function parameters to pass parameters . At the same time, weight removal and pruning are needed , When the present candidates When the element of is the same as the previous element , Just skip this loop ; When the currently traversed element ratio target When I was young , Because the array has been ordered , So direct return that will do , Finally, continue recursion along this node .
func combinationSum2(candidates []int, target int) [][]int {
sort.Ints(candidates)
var res [][]int
dfs(candidates, nil, target, 0, &res)
return res
}
func dfs(candidates []int, nums []int, target int, left int, res *[][]int) {
// Recursive export
if target == 0 {
tmp := make([]int, len(nums))
copy(tmp, nums)
*res = append(*res, tmp)
return
}
for i := left; i < len(candidates); i++ {
if i != left && candidates[i] == candidates[i - 1] {
// duplicate removal
continue
}
if target < candidates[i] {
// prune
return
}
// Direct transmission append(nums, candidates[i]) In fact, it includes the backtracking operation ,nums The array has not been changed
dfs(candidates, append(nums, candidates[i]), target - candidates[i], i + 1, res)
}
}
q46 Full Permutation
Answer key
This problem uses dfs To solve , The condition for judging leaf nodes is cur The length of the array and nums The length is the same , At this time cur Array add res Array . Then traverse nums Array to select numbers , To create a new branch , Inside a loop, you need to traverse cur Array , See if the selected number repeats , No problem, just continue along this branch .
func permute(nums []int) [][]int {
var res [][]int
dfs(nums, []int{
}, &res)
return res
}
func dfs(nums []int, cur []int, res *[][]int) {
if len(nums) == len(cur) {
tmp := make([]int, len(cur))
copy(tmp, cur)
*res = append(*res, tmp)
return
}
for i := 0; i < len(nums); i++ {
exist := false
for j := 0; j < len(cur); j++ {
if nums[i] == cur[j] {
exist = true
break
}
}
if exist == true {
continue
}
dfs(nums, append(cur, nums[i]), res)
}
}
边栏推荐
- Regulations for network security events of vocational group in 2022 Guizhou Vocational College skill competition
- 【Rust 笔记】15-字符串与文本(上)
- In depth analysis of for (VaR I = 0; I < 5; i++) {settimeout (() => console.log (I), 1000)}
- Dichotomy, discretization, etc
- MIT-6874-Deep Learning in the Life Sciences Week 7
- Navicat连接Oracle数据库报错ORA-28547或ORA-03135
- QT判断界面当前点击的按钮和当前鼠标坐标
- Navicat連接Oracle數據庫報錯ORA-28547或ORA-03135
- On the characteristics of technology entrepreneurs from Dijkstra's Turing Award speech
- Overview of variable resistors - structure, operation and different applications
猜你喜欢

QQ电脑版取消转义符输入表情

Navicat连接Oracle数据库报错ORA-28547或ORA-03135

LaMDA 不可能觉醒吗?

Implement a fixed capacity stack

leetcode-6108:解密消息

Solution to game 10 of the personal field

QQ computer version cancels escape character input expression

Typical use cases for knapsacks, queues, and stacks

Erreur de connexion Navicat à la base de données Oracle Ora - 28547 ou Ora - 03135

Arduino 控制的 RGB LED 无限镜
随机推荐
快速使用Amazon MemoryDB并构建你专属的Redis内存数据库
Wazuh开源主机安全解决方案的简介与使用体验
The sum of the unique elements of the daily question
SPI details
Some common problems in the assessment of network engineers: WLAN, BGP, switch
One question per day 1447 Simplest fraction
LeetCode 1200. Minimum absolute difference
Dynamic planning solution ideas and summary (30000 words)
Appium automation test foundation - Summary of appium test environment construction
One question per day 1020 Number of enclaves
【Rust 笔记】13-迭代器(下)
Doing SQL performance optimization is really eye-catching
One question per day 1765 The highest point in the map
数据可视化图表总结(一)
1040 Longest Symmetric String
【Rust 笔记】14-集合(上)
1.13 - RISC/CISC
leetcode-6109:知道秘密的人数
Is it impossible for lamda to wake up?
1.15 - input and output system