Last active
April 11, 2020 08:48
-
-
Save shanab/68e4d9a65002ca21885836e11f999583 to your computer and use it in GitHub Desktop.
Permutations in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func permutations(a []int) [][]int { | |
var results [][]int | |
permute(a, 0, func(a []int) { | |
results = append(results, a) | |
}) | |
return results | |
} | |
func permute(a []int, start int, f func([]int)) { | |
if start >= len(a) { | |
c := make([]int, len(a)) | |
copy(c, a) | |
f(c) | |
return | |
} | |
for i := start; i < len(a); i++ { | |
a[i], a[start] = a[start], a[i] | |
permute(a, start+1, f) | |
a[start], a[i] = a[i], a[start] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment