[LeetCode][JavaScript]Permutations II

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].

https://leetcode.com/problems/permutations-ii/

 

 


 

 

全排列,入参数组中的数字可能有重复。

第一种做法是接着Permutations,开一个哈希表记录出现过的组合。

http://www.cnblogs.com/Liok3187/p/4986918.html

 

 1 /**
 2  * @param {number[]} nums
 3  * @return {number[][]}
 4  */
 5 var permuteUnique2 = function(nums) {
 6     var result = [], visited = {};
 7     getPermute(0);
 8     return result;
 9 
10     function getPermute(index){
11         if(index === nums.length){
12             var id = nums.join('#');
13             if(!visited[id]){
14                 result.push(nums.slice(0));
15                 visited[id] = true;
16             }
17             return;
18         }
19         for(var i = index; i < nums.length; i++){
20             switchNum(i, index);
21             getPermute(index + 1);
22             switchNum(i, index);
23         }
24     }
25     function switchNum(i, j){
26         if(i === j) return;
27         var tmp = nums[i];
28         nums[i] = nums[j];
29         nums[j] = tmp;
30     }
31 };

 

第二种做法是接着Next Permutation,不断求下一个排列直到重复为止。

http://www.cnblogs.com/Liok3187/p/5010337.html

 

 1 /**
 2  * @param {number[]} nums
 3  * @return {number[][]}
 4  */
 5 var permuteUnique = function(nums) {
 6     var res = [nums.slice(0)], numsJSON = JSON.stringify(nums);
 7     while(true){
 8         nextPermutation(nums);
 9         if(numsJSON !== JSON.stringify(nums)){
10             res.push(nums.slice(0));
11         }else{
12             break;
13         }
14     }
15     return res;
16 
17     function nextPermutation(nums) {
18         for(var i = nums.length - 1; i > 0 && nums[i] <= nums[i - 1]; i--);
19         if(i === 0){
20             reverse(0, nums.length - 1);
21             return;
22         }
23         for(var j = i + 1; j < nums.length && nums[i - 1] < nums[j]; j++);
24         swap(i - 1, j - 1);
25         reverse(i, nums.length - 1);
26         return;    
27         
28         function reverse(start, end){
29             while(start < end){
30                 swap(start, end);
31                 start++;
32                 end--;
33             }
34         }
35         function swap(i, j){
36             var tmp = nums[i];
37             nums[i] = nums[j];
38             nums[j] = tmp;
39         }
40     }
41 };

 

 
posted @ 2015-12-01 16:08  `Liok  阅读(336)  评论(0编辑  收藏  举报