您的位置:首页 > 其它

[Leetcode] Permutations II

2015-08-12 16:27 423 查看
The difference betweent Problem Permutation I and Permuation II lies in the duplicates elements may exist in the second one.

For the first one , the enumeration strategy is applied. This one can also reuse that method. However, the difficulty here is how to avoid the selection of the same element as the head of the list.

We can sort the list first, when faced with the same element with the head one, we just skip it. Amazing attribute of this method is the we just need to swap the head current and the selected next element without swap back operation, as after next swap ,the left list is still in order. We can take an example

1,1,2,2,2,3,4

we select 1, 1,2,2,2,3,4

we select 2, swap 1 and 2,get

2, 1,1,2,2,3,4

we selct 3, swap 2 and 3,get

3, 1,1,2,2,2,4

we select 4,swap 3 and 4,get

4, 1,1,2,2,2,3

the swap back operation is not conducted, but the remaining part is still sorted. The reason lies in that the head element is swap back to its right position during the next head swap.

The code is listed as below.

public class Solution {
private void backtrack(List<List<Integer> > lists, List<Integer> list, int [] nums, int index){
if(index==nums.length){
List<Integer> l = new LinkedList<Integer>();
l.addAll(list);
lists.add(l);
return;
}
//Arrays.sort(nums,index,nums.length);
for(int i=index;i<nums.length;i++){

if(i!=index&&nums[i]==nums[index]){
continue;
}
int tmp=nums[index];
nums[index]=nums[i];
nums[i]=tmp;
list.add(nums[index]);
backtrack(lists,list,nums,index+1);
list.remove(list.size()-1);
}
Arrays.sort(nums,index,nums.length);
}
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
List<List<Integer> > lists =new LinkedList<List<Integer> >();
List<Integer> list = new LinkedList<Integer>();
backtrack(lists,list,nums,0);
return lists;
}
}


After each for loop we should sort the disordered list into ordered, because in the up recursive layer, the algorithm need the sorted element.

A more simple Solution

public class Solution {
private void DFS(List<List<Integer>> res, int []nums,int start){
if(start==nums.length){
List<Integer> tmpres = new LinkedList<Integer>();
for(int num: nums) tmpres.add(num);
res.add(tmpres);
return;
}
for(int i=start;i<nums.length;i++){
if(i!=start&&nums[i]==nums[start]) continue;
int tmp = nums[start];
nums[start]=nums[i];
nums[i]=tmp;
DFS(res,nums,start+1);
}
Arrays.sort(nums,start,nums.length);
}
public List<List<Integer>> permuteUnique(int[] nums) {
//sort the array first
Arrays.sort(nums);
List<List<Integer>> res = new LinkedList<List<Integer>>();
DFS(res,nums,0);
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: