Permutations without recursive function call

前端 未结 8 1017
北荒
北荒 2020-11-27 04:15

Requirement: Algorithm to generate all possible combinations of a set , without duplicates , or recursively calling function to return results.

The majority , if not

相关标签:
8条回答
  • 2020-11-27 05:08

    One method to create permutations is by adding each element in all of the spaces between elements in all of the results so far. This can be done without recursion using loops and a queue.

    JavaScript code:

    function ps(a){
      var res = [[]];
    
      for (var i=0; i<a.length; i++){
        while(res[res.length-1].length == i){
          var l = res.pop();
          for (var j=0; j<=l.length; j++){
            var copy = l.slice();
            copy.splice(j,0,a[i]);
            res.unshift(copy);
          }
        }
      }
      return res;
    }
    
    console.log(JSON.stringify(ps(['a','b','c','d'])));
    
    0 讨论(0)
  • 2020-11-27 05:14

    I think this post should help you. The algorithm should be easily translatable to JavaScript (I think it is more than 70% already JavaScript-compatible).

    slice and reverse are bad calls to use if you are after efficiency. The algorithm described in the post is following the most efficient implementation of the next_permutation function, that is even integrated in some programming languages (like C++ e.g.)

    EDIT

    As I iterated over the algorithm once again I think you can just remove the types of the variables and you should be good to go in JavaScript.

    EDIT

    JavaScript version:

    function nextPermutation(array) {
        // Find non-increasing suffix
        var i = array.length - 1;
        while (i > 0 && array[i - 1] >= array[i])
            i--;
        if (i <= 0)
            return false;
    
        // Find successor to pivot
        var j = array.length - 1;
        while (array[j] <= array[i - 1])
            j--;
        var temp = array[i - 1];
        array[i - 1] = array[j];
        array[j] = temp;
    
        // Reverse suffix
        j = array.length - 1;
        while (i < j) {
            temp = array[i];
            array[i] = array[j];
            array[j] = temp;
            i++;
            j--;
        }
        return true;
    }
    
    0 讨论(0)
提交回复
热议问题