Leetcode47. Permutations II

 1 class Solution {
 2     public List<List<Integer>> permuteUnique(int[] nums) {
 3         List<List<Integer>> ans = new ArrayList<>();
 4         if(nums==null||nums.length==0) return ans;
 5         boolean[] used = new boolean[nums.length];
 6         helper(ans,new ArrayList<>(),nums,used);
 7         return ans;
 8     }
 9     private void helper(List<List<Integer>> ans,List<Integer> tempList,int[] nums,boolean[] used){
10         if(tempList.size()==nums.length&&!ans.contains(tempList)) ans.add(new ArrayList<>(tempList));
11         else{
12             for(int i=0;i<nums.length;i++){
13                 if(used[i]) continue;
14                 tempList.add(nums[i]);
15                 used[i] = true;
16                 helper(ans,tempList,nums,used);
17                 tempList.remove(tempList.size()-1);
18                 used[i]=false;
19             }
20         }
21     }
22 }

320ms,5%。极慢…应该差在第10行的去重了。

 1 class Solution{
 2     public List<List<Integer>> permuteUnique(int[] nums) {
 3         List<List<Integer>> list = new ArrayList<>();
 4         Arrays.sort(nums);  //to remove duplicates
 5         backtrack(list, new ArrayList<>(), nums, new boolean[nums.length]);
 6         return list;
 7     }
 8 
 9     private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums, boolean [] used){
10         if(tempList.size() == nums.length){
11             list.add(new ArrayList<>(tempList));
12         } else{
13             for(int i = 0; i < nums.length; i++){
14                 if(used[i] || i > 0 && nums[i] == nums[i-1] && !used[i - 1]) continue; 
15                 /*Upper Line:with ordered nums remove duplicates.
16                 i>0: this element is not the first in this loop
17                 nums[i] == nums[i-1]: duplicate situation
18                 !used[i-1]: nums[i-1] is not currently used.If nums[i-1] is currently used then it is not a duplicate situation.*/
19                 used[i] = true; 
20                 tempList.add(nums[i]);
21                 backtrack(list, tempList, nums, used);
22                 used[i] = false; 
23                 tempList.remove(tempList.size() - 1);
24             }
25         }
26     }
27 }

5ms,53.9%。够了。

想了想,用fre数组代替tempList不一定快太多,因为最后还是要建一个tempList add到ans中去,节省的时间只有试错时remove的时间。所以backtracking问题都用这个套路挺好的。

此解法好像有误。

posted @ 2018-12-27 15:28  大胖子球花  阅读(113)  评论(0)    收藏  举报