kotlin求排列组合
时间: 2023-07-01 11:11:38 浏览: 79
可以使用 Kotlin 的递归函数来求排列组合。以下是一个示例代码:
```kotlin
fun permutations(n: Int, k: Int): List<List<Int>> {
val result = mutableListOf<List<Int>>()
val curr = mutableListOf<Int>()
val visited = BooleanArray(n)
permutationsHelper(n, k, curr, visited, result)
return result
}
fun permutationsHelper(n: Int, k: Int, curr: MutableList<Int>, visited: BooleanArray, result: MutableList<List<Int>>) {
if (curr.size == k) {
result.add(curr.toList())
return
}
for (i in 0 until n) {
if (!visited[i]) {
visited[i] = true
curr.add(i + 1)
permutationsHelper(n, k, curr, visited, result)
curr.removeAt(curr.lastIndex)
visited[i] = false
}
}
}
fun combinations(n: Int, k: Int): List<List<Int>> {
val result = mutableListOf<List<Int>>()
val curr = mutableListOf<Int>()
combinationsHelper(n, k, 1, curr, result)
return result
}
fun combinationsHelper(n: Int, k: Int, start: Int, curr: MutableList<Int>, result: MutableList<List<Int>>) {
if (curr.size == k) {
result.add(curr.toList())
return
}
for (i in start..n) {
curr.add(i)
combinationsHelper(n, k, i + 1, curr, result)
curr.removeAt(curr.lastIndex)
}
}
```
在这个示例中,`permutations` 函数接收两个参数 `n` 和 `k`,分别表示从 `n` 个数中选取 `k` 个数进行排列。它首先创建一个空的列表 `result`,然后调用 `permutationsHelper` 函数来生成所有可能的排列,并将它们添加到 `result` 列表中。最后,`permutations` 函数返回 `result` 列表。
`combinations` 函数与 `permutations` 函数类似,不同之处在于它生成的是组合而不是排列。
在 `permutationsHelper` 函数中,`visited` 数组用于记录哪些数已经被选取了。如果一个数被选取了,那么它在 `visited` 数组中对应的位置为 `true`。在每次循环中,如果当前数没有被选取过,那么就将它添加到 `curr` 列表中,并将它在 `visited` 数组中对应的位置设为 `true`。然后递归调用 `permutationsHelper` 函数,继续选取下一个数。当递归返回时,将刚刚添加的数从 `curr` 列表中删除,并将它在 `visited` 数组中对应的位置设为 `false`,以便进行下一次循环。
在 `combinationsHelper` 函数中,与 `permutationsHelper` 函数类似,也是递归函数。对于每个循环,将当前数添加到 `curr` 列表中,并递归调用 `combinationsHelper` 函数,继续选取下一个数。当递归返回时,将刚刚添加的数从 `curr` 列表中删除,以便进行下一次循环。