順列全探索

Share:
 1func permutationSearch(n int, fn func(a []int)) {
 2	a := make([]int, n)
 3	for i := 0; i < n; i++ {
 4		a[i] = i
 5	}
 6	swap := func(i, j int) { a[i], a[j] = a[j], a[i] }
 7
 8	fn(a)
 9	for i := n - 2; i >= 0; i-- {
10		if a[i] > a[i+1] {
11			continue
12		}
13		for j := n - 1; j >= 0; j-- {
14			if a[i] > a[j] {
15				continue
16			}
17			swap(i, j)
18			for k := i + 1; k < (n+i+1)/2; k++ {
19				swap(k, n-(k-i))
20			}
21			fn(a)
22			i = n - 1
23			break
24		}
25	}
26}
27