Permutations without recursive function call

前端 未结 8 1056
北荒
北荒 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:03

    I dare to add another answer, aiming at answering you question regarding slice, concat, reverse.

    The answer is it is possible (almost), but it would not be quite effective. What you are doing in your algorithm is the following:

    • Find the first inversion in the permutation array, right-to-left (inversion in this case defined as i and j where i < j and perm[i] > perm[j], indices given left-to-right)
    • place the bigger number of the inversion
    • concatenate the processed numbers in reversed order, which will be the same as sorted order, as no inversions were observed.
    • concatenate the second number of the inversion (still sorted in accordsnce with the previos number, as no inversions were observed)

    This is mainly, what my first answer does, but in a bit more optimal manner.

    Example

    Consider the permutation 9,10, 11, 8, 7, 6, 5, 4 ,3,2,1 The first inversion right-to-left is 10, 11. And really the next permutation is: 9,11,1,2,3,4,5,6,7,8,9,10=9concat(11)concat(rev(8,7,6,5,4,3,2,1))concat(10)

    Source code Here I include the source code as I envision it:

    var nextPermutation = function(arr) {
      for (var i = arr.length - 2; i >= 0; i--) {
         if (arr[i] < arr[i + 1]) {
            return arr.slice(0, i).concat([arr[i + 1]]).concat(arr.slice(i + 2).reverse()).concat([arr[i]]);
         }
      }
      // return again the first permutation if calling next permutation on last.
      return arr.reverse();
    }
    
    console.log(nextPermutation([9, 10, 11, 8, 7, 6, 5, 4, 3, 2, 1]));
    console.log(nextPermutation([6, 5, 4, 3, 2, 1]));
    console.log(nextPermutation([1, 2, 3, 4, 5, 6]));
    

    The code is avaiable for jsfiddle here.

提交回复
热议问题