How to improve efficiency of algorithm which generates next lexicographic permutation?

后端 未结 3 1094
遥遥无期
遥遥无期 2020-12-03 06:18

It must be noted here that I performed the mathematics by hand on paper to derive the foregoing proofs. I am not sure if the proofs would have become apparent by solely usin

3条回答
  •  再見小時候
    2020-12-03 06:43

    Lack of skills in maths and english makes it hard for me to elaborate on such a question :-| Though I wanted to play with permutations and I did something not so off-topic after all. See TL;DR at https://stackoverflow.com/a/43302308/1636522, I have the same feeling and I'll try to demonstrate the validity of my algorithm later, I need a little time to think of it.

    var a = "aceg".split(""); 
    do {
      console.log(a.join(""));
    } while (a = next(a));
    
    function next (a) {
      var i, c, head, next;
      var b = a.slice();
      var n = b.length;
      for (i = 1; i < n; i++) {
        if (b[n - i] > b[n - (i + 1)]) {
          head = n - (i + 1);
          next = n - i;
          for (i = next + 1; i < n; i++) {
            if (b[i] < b[next] && b[i] > b[head]) {
              next = i;
            }
          }
          c = b[head];
          b[head] = b[next];
          b[next] = c;
          return b.slice(0, head + 1).concat(
            b.slice(head + 1).sort()
          );
        }
      }
    }

提交回复
热议问题