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 { boolean isUsed[]; List<List<Integer>> result; List<Integer> list; public List<List<Integer>> permuteUnique(int[] num) { isUsed = new boolean[num.length]; result = new ArrayList<List<Integer>>(); list = new ArrayList<Integer>(); Arrays.sort(num); permute(num); return result; } private void permute(int[] num) { if (list.size() == num.length) { result.add(new ArrayList<Integer>(list)); return; } for (int i = 0; i < num.length; i++) { if (isUsed[i]) continue; if (i > 0 && num[i - 1] == num[i] && (!isUsed[i - 1])) continue; isUsed[i] = true; list.add(num[i]); permute(num); list.remove(list.size() - 1); isUsed[i] = false; } } }
原文地址:http://blog.csdn.net/guorudi/article/details/39497023