对于小型数组,您可以使用其中一种引用算法,将每个排列映射到一个字符串,然后将整个数组放入 Set 以丢弃重复项。比如:
let a = ['^','^','>','>','+','<','<'];
let ps = permutations(a); // return value should be array of arrays.
let qs = ps.map(p => p.join(""));
let s = new Set(qs);
这应该适用于带有< 10 符号的数组。
否则,请参阅 here 和 here 了解可以转换为 JavaScript 的各种方法。
一种流行的方法是Pandita algorithm,它使用继承规则按字典顺序枚举排列,有效地只生成“唯一”排列。 here 和 here 对此方法进行了简短说明。这是一个 JavaScript (ES6) 实现:
function swap(a, i, j) {
const t = a[i];
a[i] = a[j];
a[j] = t;
}
function reverseSuffix(a, start) {
if (start === 0) {
a.reverse();
}
else {
let left = start;
let right = a.length - 1;
while (left < right)
swap(a, left++, right--);
}
}
function nextPermutation(a) {
// 1. find the largest index `i` such that a[i] < a[i + 1].
// 2. find the largest `j` (> i) such that a[i] < a[j].
// 3. swap a[i] with a[j].
// 4. reverse the suffix of `a` starting at index (i + 1).
//
// For a more intuitive description of this algorithm, see:
// https://www.nayuki.io/page/next-lexicographical-permutation-algorithm
const reversedIndices = [...Array(a.length).keys()].reverse();
// Step #1; (note: `.slice(1)` maybe not necessary in JS?)
const i = reversedIndices.slice(1).find(i => a[i] < a[i + 1]);
if (i === undefined) {
a.reverse();
return false;
}
// Steps #2-4
const j = reversedIndices.find(j => a[i] < a[j]);
swap(a, i, j);
reverseSuffix(a, i + 1);
return true;
}
function* uniquePermutations(a) {
const b = a.slice().sort();
do {
yield b.slice();
} while (nextPermutation(b));
}
let a = ['^','^','>','>','+','<','<'];
let ps = Array.from(uniquePermutations(a));
let qs = ps.map(p => p.join(""));
console.log(ps.length);
console.log(new Set(qs).size);
nextPermutation 函数将数组就地转换为字典序的后继数组,或者如果数组已经是字典序的最大值,则将其转换为字典序的最小值。在第一种情况下,它返回true,否则返回false。这允许您从最小(排序)数组开始循环遍历所有排列,直到nextPermutation 翻转并返回false。