LeetCode046——全排列

版权声明:版权所有,转载请注明原网址链接。 https://blog.csdn.net/qq_41231926/article/details/82766757

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/permutations/description/

题目描述:

知识点:递归、回溯

思路:回溯法穷举所有可能的排列

本题是回溯法的一个经典应用场景,思路很清晰,逻辑很简单,下面写几个注意点。

(1)在类的内部新建一个List<List<Integer>>型的变量listList,可以避免在递归过程中一直传递该变量。

(2)递归到底,往listList中新增元素时,注意需要new一个ArrayList,因为递归过程中传递的list由于回溯过程中变量的手动回溯过程,其指向的值是一直在变化的。我们需要记录的是递归到底时list中存放的是什么值。

时间复杂度是O(n !)级别的,其中n为nums数组的长度,而空间复杂度就是递归深度,是O(n)级别的。

JAVA代码:

public class Solution {

	List<List<Integer>> listList;
	
	public List<List<Integer>> permute(int[] nums) {
		listList = new ArrayList<>();
		permute(nums, new ArrayList<>());
		return listList;
	}
	
	//we put the possible array in list, we are going to find next number
	private void permute(int[] nums, List<Integer> list) {
		int n = nums.length;
		if(list.size() == n) {
			listList.add(new ArrayList<>(list));
			return;
		}
		for (int i = 0; i < n; i++) {
			if(list.contains(nums[i])) {
				continue;
			}
			list.add(nums[i]);
			permute(nums, list);
			list.remove(list.size() - 1);
		}
	}
}

LeetCode解题报告:

扫描二维码关注公众号,回复: 3404535 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/82766757
今日推荐