[LeetCode] 46. Permutations(全排列)
Posted Zhongju.copy()
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 46. Permutations(全排列)相关的知识,希望对你有一定的参考价值。
-
Difficulty: Medium
-
Related Topics: Backtracking
Description
Given a collection of distinct integers, return all possible permutations.
给定一个各不相同的整数集合,返回其全排列。
Example
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
Solution
回溯问题有两个大类:排列树和组合树,二者都有其固定的代码模式。本题属于排列树,具体代码如下:
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(全排列)的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 46. Permutations(全排列)