您的位置:首页 > 其它

LeetCode 47 Permutations II

2016-06-05 03:01 465 查看
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 List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
backtrack(result, new ArrayList<Integer>(), nums, new boolean[nums.length]);
return result;
}

private static void backtrack(List<List<Integer>> result, ArrayList<Integer> tempList, int[]
nums, boolean[] used) {
if (tempList.size() == nums.length) {
result.add(new ArrayList<>(tempList));
} else {
for (int i = 0; i < nums.length; i++) {
/**only insert duplicate element
when the previous duplicate element has been inserted*/
if (used[i] || i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue;
used[i] = true;
tempList.add(nums[i]);
backtrack(result, tempList, nums, used);
used[i] = false;
tempList.remove(tempList.size() - 1);
}
}
}


方法二:

public List<List<Integer>> permuteUnique3(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
result.add(new ArrayList<Integer>());
for (int i = 0; i < nums.length; i++) {
List<List<Integer>> newres = new ArrayList<>();
for (List<Integer> k : result) {
for (int j = 0; j <= k.size(); j++) {
if (j>0 && k.get(j-1) == nums[i]) break;//注意这里的判断和break
List<Integer> list = new ArrayList<>(k);
list.add(j, nums[i]);
newres.add(list);
}
}
result = newres;
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode wr