标签:link 代码 kotlin remove move script ref turn difficult
Difficulty: Medium
Related Topics: Backtracking
Given a collection of distinct integers, return all possible permutations.
给定一个各不相同的整数集合,返回其全排列。
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
回溯问题有两个大类:排列树和组合树,二者都有其固定的代码模式。本题属于排列树,具体代码如下:
class Solution {
fun permute(nums: IntArray): List<List<Int>> {
val result = arrayListOf<List<Int>>()
backtrack(nums, result, arrayListOf())
return result
}
private fun backtrack(nums: IntArray, result: MutableList<List<Int>>, curList: MutableList<Int>) {
if (curList.size == nums.size) {
result.add(ArrayList(curList))
return
}
for (num in nums) {
if (curList.contains(num)) {
continue
}
curList.add(num)
backtrack(nums, result, curList)
curList.removeAt(curList.lastIndex)
}
}
}
[LeetCode] 46. Permutations(全排列)
标签:link 代码 kotlin remove move script ref turn difficult
原文地址:https://www.cnblogs.com/zhongju/p/13877895.html