Apply recursion and backtracking
Apply recursion and backtracking
Recursion solves a problem using smaller instances and a base case. Backtracking explores choices, recursively tries each branch, and undoes the choice before moving on. Use it when the search space is small enough or pruning can reduce it.
package main
import ( "fmt")
func sum(a []int) int { if len(a) == 0 { return 0 } return a[0] + sum(a[1:])}func main() { fmt.Println(sum([]int{2, 3, 4}), sum(nil))}The empty slice is the base case. Each call shortens the slice by one, guaranteeing termination. Time and stack depth are O(n); a loop avoids the stack cost for this simple problem. Assume the sum fits int.
Expected output:
9 0Enumerate subsets
package main
import ( "fmt")
func subsets(a []int) [][]int { var out [][]int path := []int{} var visit func(int) visit = func(i int) { if i == len(a) { out = append(out, append([]int(nil), path...)) return } visit(i + 1) path = append(path, a[i]) visit(i + 1) path = path[:len(path)-1] } visit(0) return out}func main() { for _, s := range subsets([]int{1, 2}) { fmt.Println(s) }}At each index choose exclusion then inclusion. Undo inclusion by shortening path. Copy path at a leaf so later changes do not overwrite saved subsets. There are 2^n positional subsets, and materializing all elements costs O(n·2^n) time and output space; duplicate input values can yield duplicate-looking results. Keep n small.
Expected output:
[][2][1][1 2]Try it locally
Count subsets whose sum equals 3 for [1,2,3], including exclusion and inclusion at each step. Print 2.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Algorithms 07: Apply recursion and backtracking
Check the lesson objective before moving on.
Why copy path before saving a subset?
What ensures recursion terminates?