How would you calculate all possible permutations of 0 through N iteratively?

后端 未结 10 2619
一向
一向 2020-12-04 15:47

I need to calculate permutations iteratively. The method signature looks like:

int[][] permute(int n)

For n = 3 for example, the r

10条回答
  •  再見小時候
    2020-12-04 16:32

    I have implemented the algorithm in Javascript.

    var all = ["a", "b", "c"];
    console.log(permute(all));
    
    function permute(a){
      var i=1,j, temp = "";
      var p = [];
      var n = a.length;
      var output = [];
    
      output.push(a.slice());
      for(var b=0; b <= n; b++){
        p[b] = b;
      }
    
      while (i < n){
        p[i]--;
        if(i%2 == 1){
          j = p[i];
        }
        else{
          j = 0;
        }
        temp = a[j];
        a[j] = a[i];
        a[i] = temp;
    
        i=1;
        while (p[i] === 0){
          p[i] = i;
          i++;
        }
        output.push(a.slice());
      }
      return output;
    }
    

提交回复
热议问题