力扣hot100 全排列 dfs 参数传递

本文分析了一个Java解决方案,用于生成给定整数数组的全排列。通过深度优先搜索(DFS)算法实现,讨论了其时间复杂度为O(n×n!)和空间复杂度为O(n)。代码中需要注意局部变量和内存管理的问题。
摘要由CSDN通过智能技术生成

Problem: 46. 全排列
在这里插入图片描述

文章目录

复杂度

时间复杂度: O ( n × n ! ) O(n×n!) O(n×n!)

空间复杂度: O ( n ) O(n) O(n)

Code1

class Solution{
	static int N = 10, n;
	static List<List<Integer>> ans;
	static int[] a;
	static boolean[] st = new boolean[N];

	public static List<List<Integer>> permute(int[] nums)
	{
		ans = new ArrayList<>();
		n = nums.length;
		a = nums;
		dfs(new ArrayList<Integer>());
//		System.out.println(System.identityHashCode(ans));
		return ans;
	}

	private static void dfs(ArrayList<Integer> list)
	{
		if (list.size() == n)
		{
//			System.out.println("方法内部" + System.identityHashCode(ans));
//			错误示例
//			ans.add(list); //这里的 list 是局部变量,每次调用完就会释放内存了,导致 ans 里边加的都是 空List
			ans.add(new ArrayList<>(list));
			return;
		}
		for (int i = 0; i < n; i++)
		{
			if (!st[i])
			{
				list.add(a[i]);
				st[i] = true;
				dfs(list);
//				恢复现场
				st[i] = false;
				list.remove(list.size() - 1);
			}
		}
	}
}

Code2

class Solution {
    static boolean[] st;
    static int n;
    static int[] nums;
    static List<List<Integer>> ans;
    public List<List<Integer>> permute(int[] nums) {
        n = nums.length;
        this.nums = nums;
        ans = new ArrayList<>();
        st = new boolean[n];
        dfs(new ArrayList<Integer>());
        return ans;
    }

    void dfs(ArrayList<Integer> list){
        if(list.size() == n)
            ans.add(new ArrayList(list));
        for(int i = 0; i < n; i++)
        {
            if(!st[i])
            {
                list.add(nums[i]);
                st[i] = true;
                dfs(list);
                list.remove(list.size() - 1);
                st[i] = false;
            }
        }
            
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值