algorithm - Permutations II, remove duplicates in recursion -
given list of numbers duplicate number in it. find unique permutations.
for numbers [1,2,2] unique permutations are: [ [1,2,2], [2,1,2], [2,2,1] ]
in method called hepler, in order remove duplicates, have if statement:
if (i != 0 && nums[i] == nums[i-1] && !set.contains(i-1) ) { continue; }
but found if change !set.contains(i - 1)
set.contains(i-1)
it's still correct(leetcode accepted), should !set.contains(i - 1)
.
anyone know reasons?
class solution { /** * @param nums: list of integers. * @return: 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; } (int = 0; < 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); } } }
wiki page describes permutation algorithm next lexicographic permutation, works repeated elements. pseudocode:
initialisation: start sorted combination - here [1,2,2] next permutation step: find largest index k such a[k] < a[k + 1]. if no such index exists, permutation last permutation. find largest index l greater k such a[k] < a[l]. swap value of a[k] of a[l]. reverse sequence a[k + 1] , including final element a[n].
Comments
Post a Comment