Thursday, January 8, 2015

LeetCode 47: Permutations II

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], and [2,1,1].
public class Solution {
    private List<List<Integer>> result;
    
    public List<List<Integer>> permuteUnique(int[] num) {
        // BackTracking problem
        result = new LinkedList<>();
        
        backTrack(num, 0);
        
        return result;
    }
    
    private void backTrack(int[] num, int i)
    {
        if (i == num.length)
        {
            List<Integer> ret = new LinkedList<>();
            
            for (int number : num)
                ret.add(number);
                
            result.add(ret);
            
            return;
        }
        else
        {
            for (int j = i; j < num.length; j++) // Note: j start from i
            {
                if (containDup(num, i, j))
                    continue;
                    
                swap(num, i, j);
                backTrack(num, i+1);
                swap(num, i, j);
            }
        }
    }
    
    // Check if there is duplicate of a[end] in a[start : end-1]
    // If has duplicate, it indicates that we have tried this permutation
    private boolean containDup(int[] a, int start, int end)
    {
        for (int i = start; i < end; i++)
            if (a[i] == a[end])
                return true;
                
        return false;
    }
    
    private void swap(int[] a, int i, int j)
    {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}

No comments:

Post a Comment