【算法题解】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]] 

示例 2:

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

示例 3:

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

提示:

  • 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);
        }
        
    }
}
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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

i余数

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值