LeetCode047——全排列II

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

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

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

题目描述:

知识点:递归、回溯

思路:回溯法结合哈希表寻找所有可能的排列

本题和LeetCode046——全排列的差别类似LeetCode040——组合总和IILeetCode039——组合总和的差别,都是在回溯法的基础上增加了哈希表的知识点。下面写几个编程中的注意点。

(1)如果在遍历哈希表的同时,修改哈希表对应的键或者键值,会报ConcurrentModificationException异常。因此我们每一次递归都需要根据hashMap新建一个类型为HashMap<Integer, Integer>的tempHashMap变量。在传递给下一层递归函数以及变量回溯过程我们都使用temp,而在遍历时我们使用hashMap,以避免ConcurrentModificationException异常。

(2)往哈希表中新增值和删除值的过程比较复杂,可以抽取出两个函数简化我们的程序书写过程。

时间复杂度是O(n ^ n)级别的,其中n为nums数组的非重复元素的个数。而空间复杂度就是递归深度,是O(n)级别的。

JAVA代码:

public class Solution {
	
	List<List<Integer>> listList;

	public List<List<Integer>> permuteUnique(int[] nums) {
		listList = new ArrayList<>();
		HashMap<Integer, Integer> hashMap = new HashMap<>();
		for (int i = 0; i < nums.length; i++) {
			addToHashMap(hashMap, nums[i]);
		}
		permuteUnique(hashMap, new ArrayList<>());
		return listList;
	}
	
	//we put the possible array in list, we are going to find next number
	private void permuteUnique(HashMap<Integer, Integer> hashMap, List<Integer> list) {
		if(hashMap.isEmpty()) {
			listList.add(new ArrayList<>(list));
			return;
		}
		HashMap<Integer, Integer> tempHashMap = new HashMap<>(hashMap);
		for (Integer integer : hashMap.keySet()) {
			list.add(integer);
			delFromHashMap(tempHashMap, integer);
			permuteUnique(tempHashMap, list);
			addToHashMap(tempHashMap, integer);
			list.remove(list.size() - 1);
		}
	}
	
	private void addToHashMap(HashMap<Integer, Integer> hashMap, int num) {
		if(hashMap.containsKey(num)) {
			hashMap.put(num, hashMap.get(num) + 1);
		}else {
			hashMap.put(num, 1);
		}
	}
	
	private void delFromHashMap(HashMap<Integer, Integer> hashMap, int num) {
		hashMap.put(num, hashMap.get(num) - 1);
		if(hashMap.get(num) == 0) {
			hashMap.remove(num);
		}
	}
}

LeetCode解题报告:

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

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/82766873