[LeetCode] 47. Permutations II Java

题目:

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:

[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

题意及分析:这道题和上一题多了一个重复值的情况,所以不能直接用元素是否在arraylist存在来作为边界条件。我这里使用一个boolean temp[nums.length]来判断nums[i]是否使用过,然后边界条件就变成 (1)当前元素没有被用过即temp[i]==false,(2)当前元素的前一个元素若没有被使用过即temp[i-1]==false,那么nums[i]!=nums[i-1],这里主要是去重。 具体看代码:

代码:

public class Solution {
	
	
	 public List<List<Integer>> permuteUnique(int[] nums) {
			List<List<Integer>> list=new ArrayList<>();
			List<Integer> array=new ArrayList<>();
			Arrays.sort(nums);
			
			int n=nums.length;
			boolean[] temp=new boolean[nums.length];
			backtracking(list, array, 0, n,nums,temp);
			return list;
	    }
		
	 public void backtracking(List<List<Integer>> list,List<Integer> array,int t,int n,int[] nums,boolean[] temp) {
			if(t>n) return;
			else if(t==n){
				list.add(new ArrayList<>(array));
			}else{
				for(int i=0;i<n;i++){
					if(temp[i]||(i>0&&nums[i]==nums[i-1]&&!temp[i-1])) continue;
					array.add(nums[i]);
					temp[i]=true;
					backtracking(list, array, t+1, n, nums,temp);
					array.remove(array.size()-1);
					temp[i]=false;
				}
			}
		}
}

  

原文地址:https://www.cnblogs.com/271934Liao/p/6950268.html