您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]Permutations

2015-11-22 22:08 676 查看

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/

数字排列。

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

/**
* @param {number[]} nums
* @return {number[][]}
*/
var permute = function(nums) {
var result = [];
getPermute(0);
return result;

function getPermute(index){
if(index === nums.length){
result.push(nums.slice(0));
return;
}
for(var i = index; i < nums.length; i++){
switchNum(i, index);
getPermute(index + 1);
switchNum(i, index);
}
}
function switchNum(i, j){
if(i === j) return;
var tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: