Javascript递归数字排列

时间:2015-10-14 18:35:23

标签: javascript recursion permutation

当我输入这个函数85时,它只返回85.我不明白为什么不再以5为第一个数字递归调用自身。

console.log(PermutationStep(85));

function PermutationStep(num) { 
  var perms = [];

  rec(String(num), String(num).length, [], '');
  return perms;

  function rec(num, numLength, used, currPerm) {
    console.log(currPerm);
    if (currPerm.length === numLength) {
      perms.push(num);
    }
    for (var j=0; j<numLength; j++) {
      if (used[j]) continue;
      else {
        used[j]=true;
        rec(num, numLength, used, currPerm+num[j]);
      }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

  1. 当达到篇幅时,您应该推送currPerm而不是num

  2. 跟踪后再次使used[j]可用。

  3. 可能会产生重复的结果,例如885,您需要确保其不会跟踪相同的值。

  4. console.log(PermutationStep(85));
    console.log(PermutationStep(885));
    
    function PermutationStep(num) { 
      var perms = [];
      
      // Convert number to char array.
      var str = ('' + num).split('');
      var length = str.length;
      // sort by alphabetical order.
      str.sort(function(a, b) {
        return a - b;
      });
    
      // Create used map.
      var used = str.map(function() {
        return false;
      });
    
      rec(str, '');
      return perms;
    
      // Not that javascript can reference value from outer function scope,
      // So we don't need to pass length and used each time, like you treat with perms.
      function rec(num, currPerm) {
        console.log(currPerm);
        if (currPerm.length === length) {
          // Put the constructed string here, not num
          perms.push(currPerm);
        }
        var prev = null, ch;
        for (var j = 0; j < length; j++) {
          if (used[j]) {
            continue;
          }
          ch = str[j];
          if (prev === ch) { 
            // If current char is same wih previous, there's more than 2 ch in the string,
            // So we need to skip to prevent duplicate result.
            continue;
          }
          used[j] = true;
          rec(num, currPerm + ch);
          // Make the number usable again.
          used[j]=false;
          prev = ch;
        }
      }
    }