Permutations without recursive function call

前端 未结 8 1059
北荒
北荒 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条回答
  •  猫巷女王i
    2020-11-27 05:01

    Here is an answer from @le_m. It might be of help.

    The following very efficient algorithm uses Heap's method to generate all permutations of N elements with runtime complexity in O(N!):

    function permute(permutation) {
      var length = permutation.length,
          result = [permutation.slice()],
          c = new Array(length).fill(0),
          i = 1, k, p;
    
      while (i < length) {
        if (c[i] < i) {
          k = i % 2 && c[i];
          p = permutation[i];
          permutation[i] = permutation[k];
          permutation[k] = p;
          ++c[i];
          i = 1;
          result.push(permutation.slice());
        } else {
          c[i] = 0;
          ++i;
        }
      }
      return result;
    }
    
    console.log(JSON.stringify(permute([1, 2, 3, 4])));

提交回复
热议问题