Skip to content

Commit b0758f5

Browse files
committed
feat(solutions): add permutation_sequence
1 parent 1c9e788 commit b0758f5

File tree

3 files changed

+79
-0
lines changed

3 files changed

+79
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# 60. Permutation Sequence
2+
3+
## Description
4+
5+
The set `[1,2,3,…,_n_]` contains a total of _n_! unique permutations.
6+
7+
By listing and labeling all of the permutations in order,
8+
9+
We get the following sequence (ie, for _n_ = 3):
10+
11+
1. `“123“`
12+
2. `“132“`
13+
3. `“213“`
14+
4. `“231“`
15+
5. `“312“`
16+
6. `“321“`
17+
18+
Given _n_ and _k_, return the _k_th permutation sequence.
19+
20+
**Note:** Given _n_ will be between 1 and 9 inclusive.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package permutationsequence
2+
3+
func getPermutation(n int, k int) string {
4+
if k <= 0 {
5+
return ""
6+
}
7+
s := make([]byte, n)
8+
i, j, f := 1, 0, 1
9+
for ; i <= n; i++ {
10+
f *= i
11+
s[i-1] += byte('0' + i) // make s become 1234...n
12+
}
13+
for i, k = 0, k-1; i < n; i++ {
14+
f /= n - i
15+
j = i + k/f // calculate and put at s[i]
16+
temp := s[j]
17+
// remove c by shifting to cover up (adjust the right part).
18+
for ; j > i; j-- {
19+
s[j] = s[j-1]
20+
}
21+
k %= f
22+
s[i] = temp
23+
}
24+
return string(s)
25+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package permutationsequence
2+
3+
import (
4+
"testing"
5+
6+
"github.com/WindomZ/testify/assert"
7+
)
8+
9+
func TestGetPermutation(t *testing.T) {
10+
assert.Equal(t, "", getPermutation(0, 0))
11+
assert.Equal(t, "1", getPermutation(1, 1))
12+
assert.Equal(t, "123", getPermutation(3, 1))
13+
assert.Equal(t, "132", getPermutation(3, 2))
14+
assert.Equal(t, "213", getPermutation(3, 3))
15+
assert.Equal(t, "231", getPermutation(3, 4))
16+
assert.Equal(t, "312", getPermutation(3, 5))
17+
assert.Equal(t, "321", getPermutation(3, 6))
18+
}
19+
20+
func Benchmark_getPermutation(b *testing.B) {
21+
b.StopTimer()
22+
b.ReportAllocs()
23+
b.StartTimer()
24+
b.RunParallel(func(pb *testing.PB) {
25+
for pb.Next() {
26+
getPermutation(0, 0)
27+
getPermutation(1, 1)
28+
getPermutation(3, 1)
29+
getPermutation(3, 2)
30+
getPermutation(3, 3)
31+
getPermutation(3, 6)
32+
}
33+
})
34+
}

0 commit comments

Comments
 (0)