From cf0c5b94dff44b961b924a5f5bc1a228fbf3b8e4 Mon Sep 17 00:00:00 2001 From: guowenfeng <841784596@qq.com> Date: Mon, 7 Jun 2021 21:53:02 +0800 Subject: [PATCH] dfs --- .idea/workspace.xml | 26 ++++++---- .../main.go" | 50 +++++++++++++++++++ main.go | 40 +++++++++------ 3 files changed, 91 insertions(+), 25 deletions(-) create mode 100644 "leet_code/494.\347\233\256\346\240\207\345\222\214/main.go" diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 84e9488..330d9a7 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -63,13 +63,13 @@ - - + + - - + + @@ -108,11 +108,11 @@ + + - - @@ -124,11 +124,19 @@ true + + + + file://$PROJECT_DIR$/leet_code/494.目标和/main.go + 37 + + + - - - + + diff --git "a/leet_code/494.\347\233\256\346\240\207\345\222\214/main.go" "b/leet_code/494.\347\233\256\346\240\207\345\222\214/main.go" new file mode 100644 index 0000000..fc76e57 --- /dev/null +++ "b/leet_code/494.\347\233\256\346\240\207\345\222\214/main.go" @@ -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)) +} diff --git a/main.go b/main.go index 8547797..2f97923 100644 --- a/main.go +++ b/main.go @@ -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") }