当前位置:网站首页>Leetcode t47: full arrangement II

Leetcode t47: full arrangement II

2022-07-04 14:23:00 Fan Qianzhi

Title Description

Given a sequence that can contain repeating numbers nums , In any order Returns all non repeating permutations .

Example 1:

Input :nums = [1,1,2]
Output :
[[1,1,2],
[1,2,1],
[2,1,1]]

Example 2:

Input :nums = [1,2,3]
Output :[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Tips :

  • 1 <= nums.length <= 8
  • -10 <= nums[i] <= 10

Ideas

utilize HashMap duplicate removal

Code

	int n;
	int[] a;
	Map<List<Integer>, Integer> res;
	
	void prem(int cur) {
    
		if(cur == n) {
    
			List<Integer> lis = new ArrayList<Integer>();
			for(int x: a) lis.add(x);
			res.put(lis, 1);
		} else {
    
			for(int i = cur; i < n; i++) {
    
				int t = a[i]; a[i] = a[cur]; a[cur] = t;
				prem(cur+1);
				t = a[i]; a[i] = a[cur]; a[cur] = t;
			}
		}
	}
	
    public List<List<Integer>> permuteUnique(int[] nums) {
    
    	a = nums;
    	n = nums.length;
    	res = new HashMap<List<Integer>, Integer>();
    	prem(0);
    	return new ArrayList<List<Integer>>(res.keySet());
    }
	
	void test() throws IOException {
    
		Reader cin = new Reader();
		int[] a = {
    1,2,3};
		permuteUnique(a);
	}
原网站

版权声明
本文为[Fan Qianzhi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041222044514.html