我有这样的密码:

function swap (alphabets, index1, index2) {
    var temp = alphabets[index1];
    alphabets[index1] = alphabets[index2];
    alphabets[index2] = temp;
    return alphabets;
}

function permute (alphabets, startIndex, endIndex) {
    if (startIndex === endIndex) {
        console.log(alphabets.join(''));
    } else {
        var i;
        for (i = startIndex; i <= endIndex; i++) {
            swap(alphabets, startIndex, i);
            permute(alphabets, startIndex + 1, endIndex);
            swap(alphabets, i, startIndex); // backtrack
        }
    }
}

例如,如果输入是
[1,4,2]
输出将为(此输出不正确)
142 142 124 124 142 412 412 421 421 412 241 241 214 214 214 241 421 412 241 214 124 142
我希望此代码返回固定数量的数字。
例如:2个字符,[1,4,2]=>14,12,42,24,21,41;
3个字符,[1,4,2]=>142,124,421,412等等。

最佳答案

我们可以调整您提供的permute函数以累积其结果的副本,然后将其应用于固定长度的组合。

function swap (alphabets, index1, index2) {
    var temp = alphabets[index1];
    alphabets[index1] = alphabets[index2];
    alphabets[index2] = temp;
    return alphabets;
}

function permute (alphabets, startIndex, endIndex, result) {
    if (startIndex === endIndex) {
        result.push(alphabets.slice());
    } else {
        var i;
        for (i = startIndex; i <= endIndex; i++) {
            swap(alphabets, startIndex, i);
            permute(alphabets, startIndex + 1, endIndex, result);
            swap(alphabets, i, startIndex); // backtrack
        }
    }
    return result;
}

function combinations(A, k, i=0, acc=[]){
  if (A.length - i + acc.length == k)
    return [acc.concat(A.slice(i))]
  if (acc.length == k)
    return [acc]
  return combinations(A, k, i+1, acc.slice().concat(A[i]))
    .concat(combinations(A, k, i+1, acc))
}

function f(A, k){
  let result = []
  for (let comb of combinations(A, k))
    result = result.concat(permute(comb, 0, k - 1, []))
  return result
}

var A = [1, 2, 3]
console.log(JSON.stringify(f(A, 2)))
console.log(JSON.stringify(f(A, 3)))

10-07 12:34