排列II,删除递归中的重复

时间:2016-11-05 22:37:46

标签: algorithm

给出一个包含重复数字的数字列表。找到所有独特的排列。

For numbers [1,2,2] the unique permutations are:
[
  [1,2,2],
  [2,1,2],
  [2,2,1]
]

在名为hepler的方法中,为了删除重复项,我有一个if语句:

if (i != 0 && nums[i] == nums[i-1] && !set.contains(i-1) ) {
    continue;
}

但我发现如果我将!set.contains(i - 1)更改为set.contains(i-1)它仍然正确(接受leetcode),但它应该是!set.contains(i - 1)

有人知道原因吗?

class Solution {
/**
 * @param nums: A list of integers.
 * @return: A list of unique permutations.
 */
public List<List<Integer>> permuteUnique(int[] nums) {
    List<List<Integer>> list = new ArrayList<List<Integer>>();

    if (nums == null) {
        return list;
    }

    if (nums.length == 0) {
        list.add( new ArrayList<Integer>() );
        return list;
    }

    Arrays.sort(nums);

    HashSet<Integer> set = new HashSet<Integer>();
    ArrayList<Integer> current = new ArrayList<Integer>();
    helper(nums, list, current, set);

    return list;
} 

public void helper(int [] nums, 
                   List<List<Integer>> list,
                   ArrayList<Integer> current,
                   HashSet<Integer> set){

    if(current.size() == nums.length) {
        list.add( new ArrayList<Integer>(current) );
        return;
    }

    for (int i = 0; i < nums.length; i++) {

        if ( set.contains(i) ) {
            continue;
        }

        if (i != 0 && nums[i] == nums[i-1] && !set.contains(i-1) ) {
            continue;
        }

        current.add( nums[i] );
        set.add(i);
        helper(nums, list, current, set);
        set.remove(i);
        current.remove(current.size() - 1);
     }
   }
}

1 个答案:

答案 0 :(得分:0)

Wiki页面描述了permutation algorithm to get the next lexicographic permutation,它适用于重复的元素。伪代码:

Initialisation: 
     Start with sorted combination - here [1,2,2]

Next permutation step:

   Find the largest index k such that a[k] < a[k + 1]. If no such index exists, 
   the permutation is the last permutation.

   Find the largest index l greater than k such that a[k] < a[l].

   Swap the value of a[k] with that of a[l].

   Reverse the sequence from a[k + 1] up to and including the final element a[n].