码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-Permutations II

时间:2016-08-24 06:37:08      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

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]
]
public class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        if(nums==null || nums.length==0){
            return null;
        }
        List<List<Integer>> resList=new ArrayList<List<Integer>>();
        List<Integer> item=new ArrayList<Integer>();
        boolean[] isVisited=new boolean[nums.length];
        Arrays.sort(nums);
        backTracking(nums, item, resList, isVisited);
        return resList;
    }
    public void backTracking(int[] nums, List<Integer> item, List<List<Integer>> resList, boolean[] isVisited){
        if(item.size()==nums.length){
            resList.add(new ArrayList<Integer>(item));
            return;
        }
        for(int i=0; i<nums.length; i++){
            if(i>0 && nums[i]==nums[i-1] && !isVisited[i-1]){
                continue;
            }
            if(!isVisited[i]){
                item.add(nums[i]);
                isVisited[i]=true;
                backTracking(nums, item, resList, isVisited);
                item.remove(item.size()-1);
                isVisited[i]=false;
            }
        }
    }
}

 

LeetCode-Permutations II

标签:

原文地址:http://www.cnblogs.com/incrediblechangshuo/p/5801423.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!