forked from spring1843/go-dsa
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring_permutations.go
More file actions
30 lines (25 loc) · 795 Bytes
/
Copy pathstring_permutations.go
File metadata and controls
30 lines (25 loc) · 795 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package queue
import "container/list"
type state struct {
permutation string
remaining string
}
// StringPermutations solves the problem in O(n!) time and O(n!) space.
func StringPermutations(input string) []string {
output := []string{}
queue := list.New()
queue.PushBack(state{"", input})
for queue.Len() > 0 {
currentState := queue.Remove(queue.Front()).(state)
if len(currentState.permutation) == len(input) {
output = append(output, currentState.permutation)
continue
}
for i := 0; i < len(currentState.remaining); i++ {
nextPermutation := currentState.permutation + string(currentState.remaining[i])
nextRemaining := currentState.remaining[:i] + currentState.remaining[i+1:]
queue.PushBack(state{nextPermutation, nextRemaining})
}
}
return output
}