[LeetCode][JavaScript]Permutations

Permutations

Given a collection of numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[1,2,3][1,3,2][2,1,3][2,3,1][3,1,2], and [3,2,1].

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

 

 


 

 

数字排列。

循环每一位数字,每个数都和所有数交换(包括自己)。

 

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

 

 

posted @ 2015-11-22 22:08  `Liok  阅读(586)  评论(0编辑  收藏  举报