Problem

Given a collection of numbers, return all possible permutations.

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

JavaScript Code

function permute(num) {
    var result = [];
 
    //start from an empty list
    result.push([]);
 
    for (var i = 0; i < num.length; i++) {
        //list of list in current iteration of the array num
        var current = [];
 
        for (var k=0;k<result.length;k++) {
            var l = result[k];
            // # of locations to insert is largest index + 1
            for (var j = 0; j < l.length+1; j++) {
                // + add num[i] to different locations
                l.splice(j, 0, num[i]);
 
                var temp = JSON.parse(JSON.stringify(l));
                current.push(temp);                 
                
                // - remove num[i] add
                l.splice(j,1);
            }
        }
 
        result = JSON.parse(JSON.stringify(current));
    }
 
    return result;
}

0 comments:

Blogroll

Popular Posts