leetcode Permutations II

来源:互联网 发布:淘宝关键词查询 编辑:程序博客网 时间:2024/06/10 17:17

Permutations II原题地址:

https://oj.leetcode.com/problems/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 {    List<List<Integer>> list = new ArrayList<List<Integer>>();public List<List<Integer>> permuteUnique(int[] num) {if (num == null || num.length == 0)return list;Arrays.sort(num);boolean[] check = new boolean[num.length];LinkedList<Integer> temp = new LinkedList<Integer>();permutelist(num, check, temp, 0);return list;}private void permutelist(int[] num, boolean[] check, LinkedList<Integer> temp, int p) {if (p == num.length) {LinkedList<Integer> plist = (LinkedList<Integer>) temp.clone();list.add(plist);}for (int i = 0; i < num.length; i++) {if (i > 0 && num[i-1] == num[i] && !check[i-1])continue;if (!check[i]) {temp.add(num[i]);check[i] = true;permutelist(num, check, temp, p+1);temp.pollLast();check[i] = false;}}}}


0 0
原创粉丝点击