File tree Expand file tree Collapse file tree 2 files changed +69
-0
lines changed
main/kotlin/com/forketyfork/codingproblems
test/kotlin/com/forketyfork/codingproblems Expand file tree Collapse file tree 2 files changed +69
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com.forketyfork.codingproblems
2
+
3
+ import java.util.*
4
+
5
+ /* *
6
+ * Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
7
+ *
8
+ * @see "Daily Coding Problem #1128"
9
+ * @see <a href="https://leetcode.com/problems/permutations/description/">LeetCode #46. Permutations</a>
10
+ */
11
+ class Permutations {
12
+
13
+ fun permute (nums : IntArray ): List <List <Int >> = permute(LinkedList (nums.toList()))
14
+
15
+ private fun permute (nums : LinkedList <Int >): List <MutableList <Int >> {
16
+ if (nums.isEmpty()) {
17
+ return listOf (mutableListOf ())
18
+ }
19
+ return nums.indices.flatMap { idx ->
20
+ nums.removeAt(idx).let { el ->
21
+ permute(nums).also { lists ->
22
+ lists.forEach { it.add(el) }
23
+ nums.add(idx, el)
24
+ }
25
+ }
26
+ }
27
+ }
28
+
29
+ }
Original file line number Diff line number Diff line change
1
+ package com.forketyfork.codingproblems
2
+
3
+ import org.assertj.core.api.Assertions.assertThat
4
+ import org.junit.jupiter.params.ParameterizedTest
5
+ import org.junit.jupiter.params.provider.Arguments.of
6
+ import org.junit.jupiter.params.provider.MethodSource
7
+
8
+ class PermutationsTest {
9
+ companion object {
10
+ @JvmStatic
11
+ fun data () = arrayOf(
12
+ of(
13
+ intArrayOf(1 , 2 , 3 ),
14
+ listOf (
15
+ listOf (1 , 2 , 3 ),
16
+ listOf (1 , 3 , 2 ),
17
+ listOf (2 , 1 , 3 ),
18
+ listOf (2 , 3 , 1 ),
19
+ listOf (3 , 1 , 2 ),
20
+ listOf (3 , 2 , 1 )
21
+ )
22
+ ),
23
+ of(
24
+ intArrayOf(0 , 1 ),
25
+ listOf (listOf (0 , 1 ), listOf (1 , 0 ))
26
+ ),
27
+ of(
28
+ intArrayOf(1 ),
29
+ listOf (listOf (1 ))
30
+ ),
31
+ )
32
+ }
33
+
34
+ @ParameterizedTest(name = " input {0}, expected {1}" )
35
+ @MethodSource(" data" )
36
+ fun test (input : IntArray , expected : List <List <Int >>) {
37
+ assertThat(Permutations ().permute(input)).containsExactlyInAnyOrderElementsOf(expected)
38
+ }
39
+
40
+ }
You can’t perform that action at this time.
0 commit comments