当前位置:   article > 正文

【算法题解】30. 全排列的递归解法_递归算法30

递归算法30

这是一道 中等难度 的题

https://leetcode.cn/problems/permutations/

题目

给定一个不含重复数字的数组 n u m s nums nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

示例 1:

输入:nums = [1,2,3] 
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] 
  • 1
  • 2

示例 2:

输入:nums = [0,1] 
输出:[[0,1],[1,0]] 
  • 1
  • 2

示例 3:

输入:nums = [1] 
输出:[[1]] 
  • 1
  • 2

提示:

  • 1 < = n u m s . l e n g t h < = 6 1 <= nums.length <= 6 1<=nums.length<=6
  • − 10 < = n u m s [ i ] < = 10 -10 <= nums[i] <= 10 10<=nums[i]<=10
  • n u m s nums nums 中的所有整数 互不相同

题解

这道题还是 递归 的思路,以示例一 n u m s = [ 1 , 2 , 3 ] nums = [1,2,3] nums=[1,2,3] 为例:

  1. 递归函数:每次选取一个未曾选取过的元素,然后进入下一次递归。
  2. 递归边界:当 n u m s nums nums 中的所有元素都被选完时,记录答案,并返回。
  3. 还原现场:每次回退时(红色箭头)应该将本次选择的元素删除。

Java 代码实现
class Solution {

    List<List<Integer>> ans = new ArrayList<>();
    List<Integer> selected = new ArrayList<>();


    public List<List<Integer>> permute(int[] nums) {

        recursion( nums);
        return ans;
    }

    private void recursion( int[] nums){
        int n = nums.length;
        // 边界条件
        if(selected.size() == n){
            ans.add(new ArrayList(selected));
            return;
        }

        for(int i = 0; i < n; i++){
            if(selected.contains(nums[i])){
                continue;
            }
            selected.add(nums[i]);
            this.recursion( nums);
            selected.remove(selected.size() - 1);
        }
        
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
Go 代码实现
var (
    ans [][]int
    selectedVal []int
    selectedIndex []bool
)


func permute(nums []int) [][]int {
    
    ans = make([][]int, 0)
    selectedVal = make([]int, 0)
    selectedIndex = make([]bool, len(nums))

    recursion(nums)
    return ans
}

func recursion(nums []int) {
    if len(selectedVal) == len(nums) {
        temp := make([]int, len(selectedVal))
        copy(temp, selectedVal)
        ans = append(ans, temp)
        return
    }

    for i, v :=  range nums{
        if selectedIndex[i]{
            continue
        }

        selectedIndex[i] = true
        selectedVal = append(selectedVal, v)
        recursion(nums)
        selectedIndex[i] = false;
        selectedVal = selectedVal[:len(selectedVal) - 1]
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/空白诗007/article/detail/916232
推荐阅读
相关标签
  

闽ICP备14008679号