lintcode-medium-Permutations II

Posted 哥布林工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-Permutations II相关的知识,希望对你有一定的参考价值。

Given a list of numbers with duplicate number in it. Find all unique permutations.

 

Example

For numbers [1,2,2] the unique permutations are:

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

Using recursion to do it is acceptable. If you can do it without recursion, that would be great!

 

class Solution {
    /**
     * @param nums: A list of integers.
     * @return: A list of unique permutations.
     */
    public ArrayList<ArrayList<Integer>> permuteUnique(ArrayList<Integer> nums){
        // write your code here
        
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        
        if(nums == null || nums.size() == 0)
            return result;
        
        ArrayList<Integer> line = new ArrayList<Integer>();
        boolean[] visited = new boolean[nums.size()];
        
        Collections.sort(nums);
        
        helper(result, line, visited, nums);
        
        return result;
    }
    
    public void helper(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> line, boolean[] visited, ArrayList<Integer> nums){
        
        if(line.size() == nums.size()){
            result.add(new ArrayList<Integer>(line));
            return;
        }
        
        for(int i = 0; i < nums.size(); i++){
            if(visited[i])
                continue;
            else if(i > 0 && nums.get(i) == nums.get(i - 1) && !visited[i - 1])
                continue;
            
            line.add(nums.get(i));
            visited[i] = true;
            helper(result, line, visited, nums);
            line.remove(line.size() - 1);
            visited[i] = false;
            
        }
        
        return;
    }
    
    
}

 

以上是关于lintcode-medium-Permutations II的主要内容,如果未能解决你的问题,请参考以下文章