Loading

[LeetCode] 46. Permutations(全排列)

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)
        }
    }
}
posted @ 2020-10-26 12:53  Zhongju.copy()  阅读(71)  评论(0编辑  收藏  举报