文章 217
评论 7
浏览 146909
Backtracking - 46. Permutations

Backtracking - 46. Permutations

46. Permutations
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]
]

思路:

题目意思很简单就是求出一个数组的排列组合,思路就是使用回溯来做。

代码:

go:

func permute(nums []int) [][]int {

    var res [][]int
    dfs(0, nums, &res)
    return res
}

func dfs(start int, nums []int, res *[][]int){
    if start == len(nums) {
        *res = append(*res, append([]int{}, nums...))
        return 
    }
    
    for i := start; i < len(nums); i++ {
        nums[i], nums[start] = nums[start], nums[i]
        dfs(start + 1, nums, res)
        nums[start], nums[i] = nums[i], nums[start]
    }
}

标题:Backtracking - 46. Permutations
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/09/05/1567695322066.html

Nothing just happens, it's all part of a plan.

取消