`
hcx2013
  • 浏览: 88891 次
社区版块
存档分类
最新评论

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 {
    public List<List<Integer>> permuteUnique(int[] nums) {
    	List<List<Integer>> res = new ArrayList<List<Integer>>();  
        if(nums.length==0 || nums==null) {  
            return res;  
        }  
        List<Integer> item = new ArrayList<Integer>();  
        boolean[] visited = new boolean[nums.length];    
        Arrays.sort(nums);
        help(nums,res,item,visited);  
        return res;  
    }

	private void help(int[] nums, List<List<Integer>> res, List<Integer> item,
			boolean[] visited) {
		// TODO Auto-generated method stub
		if (item.size() == nums.length) {  
            res.add(new ArrayList<Integer>(item));  
        }  
        for (int i = 0; i < nums.length; i++) {  
        	if (i > 0 && nums[i] == nums[i-1] && !visited[i-1]) {
        		continue;
        	}
            if (!visited[i]) {  
                item.add(nums[i]);  
                visited[i] = true;  
                help(nums,res,item,visited);  
                item.remove(item.size()-1);  
                visited[i] = false;  
            }  
        }  
	}
}

 

 

6
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics