LeetCode之Permutations(Kotlin)

问题:



方法:
递归加着色法,然后遍历所有可能出现的情况,参考代码即可。

package com.eric.leetcode

class Permutations {
    val result = mutableListOf>()
    fun permute(nums: IntArray): List> {
        result.clear()
        val array = IntArray(nums.size) { 0 }
        for (index in nums.indices) {
            array[index] = 1
            dfs(nums, listOf(nums[index]), array)
            array[index] = 0
        }
        return result
    }

    private fun dfs(nums: IntArray, list: List, array: IntArray) {
        if (array.all { it == 1 }) {
            result.add(list)
            return
        }
        for (i in nums.indices) {
            if (array[i] == 0) {
                array[i] = 1
                dfs(nums, listOf(nums[i], *list.toTypedArray()), array)
                array[i] = 0
            }
        }
    }
}

fun main() {
    val input = intArrayOf(1, 2, 3)
    val permutations = Permutations()
    permutations.permute(input)
}

有问题随时沟通

具体代码实现可以参考Github

你可能感兴趣的:(LeetCode之Permutations(Kotlin))