Skip to content

Commit

Permalink
dfs
Browse files Browse the repository at this point in the history
  • Loading branch information
gdis5251 committed Jun 7, 2021
1 parent 791491b commit cf0c5b9
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 25 deletions.
26 changes: 17 additions & 9 deletions .idea/workspace.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

50 changes: 50 additions & 0 deletions leet_code/494.目标和/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package main

import "fmt"

func findTargetSumWays(nums []int, target int) int {
res := 0

//dfs(curSum, target, index, &res, nums, '+')
//dfs(curSum, target, index, &res, nums, '-')

dfsBetter(nums, target, 0, 0, &res)

return res
}

func dfsBetter(nums []int, target, sum, index int, res *int) {
if index == len(nums) {
if sum == target {
*res++
}
} else {
dfsBetter(nums, target, sum + nums[index], index + 1, res)
dfsBetter(nums, target, sum - nums[index], index + 1, res)
}
}

func dfs(curSum, target, index int, res *int, nums []int, op byte) {
if op == '+' {
curSum += nums[index]
} else {
curSum -= nums[index]
}
index++

if curSum == target && index == len(nums){
*res += 1
return
} else if index == len(nums) {
return
} else {
dfs(curSum, target, index, res, nums, '+')
dfs(curSum, target, index, res, nums, '-')
}
}



func main() {
fmt.Println(findTargetSumWays([]int{1, 1, 1, 1, 1}, 3))
}
40 changes: 24 additions & 16 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,36 @@ package main

import (
"fmt"
"reflect"
"os"
"time"
)

func main() {
chan1 := make(chan int, 1)
chan2 := make(chan string, 2)
chan3 := make(chan float64, 1)
defer fmt.Println("defer main")
var user = os.Getenv("USER_")

// 异步监听
go func() {
for {
// select 会等待某个管道就绪,若同时多个就绪,会随机选一个处理
select {
case params := <- chan1:
fmt.Println(params)
case <- chan2:
case <- chan3:
default:
// do nothing
defer func() {
fmt.Println("defer caller")
if err := recover(); err != nil {
fmt.Println("recover success. err: ", err)
}
}
}()

func() {
defer func() {
fmt.Println("defer here")
}()

if user == "" {
panic("should set user env.")
}

// 此处不会执行
fmt.Println("after panic")
}()
}()

reflect.SliceHeader{}
time.Sleep(100)
fmt.Println("end of main function")
}

0 comments on commit cf0c5b9

Please sign in to comment.