天天看點

Java實作-帶有重複元素的排列

給出一個具有重複數字的清單,找出清單所有不同的排列。

您在真實的面試中是否遇到過這個題?  Yes 樣例

給出清單 

[1,2,2]

,不同的排列有:

[
  [1,2,2],
  [2,1,2],
  [2,2,1]
]
           
class Solution {
    /**
     * @param nums: A list of integers.
     * @return: A list of unique permutations.
     */
    public List<List<Integer>> permuteUnique(int[] nums) {
        // Write your code here
        Arrays.sort(nums);
		List<List<Integer>> result=new ArrayList<List<Integer>>();
		List<Integer> tempList=new ArrayList<Integer>();
		boolean used[]=new boolean[nums.length];
		backTracking(nums, result, tempList, used);
		return result;
    } 
    private static void backTracking(int[] nums, List<List<Integer>> result, List<Integer> tempList, boolean []used){
		if(nums.length==tempList.size()){
			result.add(new ArrayList<Integer>(tempList));
		}else{
			for(int i=0;i<nums.length;i++){
				if(i>0&&nums[i]==nums[i-1]&&used[i-1]==false||used[i]==true){
					continue;
				}else{
					used[i]=true;
					tempList.add(nums[i]);
					backTracking(nums, result, tempList, used);
					used[i]=false;
					tempList.remove(tempList.size()-1);
				}
			}
		}
	}

}
           

繼續閱讀