46. Permutations ⭐

Medium

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Example 1:

Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Example 2:

Input: nums = [0,1]
Output: [[0,1],[1,0]]

Example 3:

Input: nums = [1]
Output: [[1]]

Constraints:

  • 1 <= nums.length <= 6

  • -10 <= nums[i] <= 10

  • All the integers of nums are unique.

解題

講得不錯的解說

Runtime: 0 ms, faster than 100%

Memory Usage: 2.5 MB, less than 87.18%

func permute(nums []int) [][]int {
    ans := make([][]int, 0)
    perm := make([]int, len(nums))
    visited := make([]bool, len(nums)) // 一個狀態變量儲存整個狀態樹

    var backtracking func(int)
    backtracking = func(index int) {
        if index == len(nums) {
            ans = append(ans, append([]int{}, perm...))
            return
        }

        for i:=0; i<len(nums); i++ {
            if !visited[i] {
                visited[i] = true
                perm[index] = nums[i]
                backtracking(index+1)   
                visited[i] = false // 撤銷選擇
            }
        }
    }

    backtracking(0)

    return ans
}

Last updated