Shuffle an array as many as possible

前端 未结 8 1375
一向
一向 2020-12-07 05:21

I have an array like this

[0,2,3]

The possible shuffling of this array are

[0,2,3], [2,3,0], [3,0,2], [3,2,0], [0,3,2],         


        
8条回答
  •  醉酒成梦
    2020-12-07 05:53

    All permutations of a set can be found by selecting an element in the set and recursively permuting (rearranging) the remaining elements. Backtracking approach can be used for finding the solution.

    Algorithm steps (source):

    enter image description here

    Pseudocode (source):

    permute(i) 
       if i == N  output A[N] 
       else 
          for j = i to N do 
             swap(A[i], A[j]) 
             permute(i+1) 
             swap(A[i], A[j])
    

    Javascript implementation (jsFiddle):

    Array.prototype.clone = function () {
        return this.slice(0);
    };
    
    var input = [1, 2, 3, 4];
    var output = [];
    
    function permute(i) {
        if (i == input.length)
            output.push(input.clone());
        else {
            for (var j = i; j < input.length; j++) {
                swap(i, j);
                permute(i + 1);
                swap(i, j); // backtrack
            }
        }
    };
    
    function swap(i, j) {
        var temp = input[i];
        input[i] = input[j];
        input[j] = temp;
    }
    
    permute(0);
    console.log(output);
    

提交回复
热议问题