构成指定长度字符串的个数(去重排列组合)
思路: 回溯
// 带重复元素的部分排列
function generateDistinctString(str, num) {
let childStr = [];
const res = [];
const fn = function (str) {
if (childStr.length === num) {
let len = num;
// 相同字符不相邻
while (len > -1) {
if (childStr[len] === childStr[len - 1]) return;
len--
}
res.push(childStr.join(''));
return;
}
let obj = {};
for (let i = 0; i < str.length; i++) {
if (obj[str[i]]) continue;
obj[str[i]] = true;
childStr.push(str[i]);
let temp = str.slice(0);
temp.splice(i, 1);
fn(temp);
childStr.pop();
}
}
str = str.split('');
fn(str);
console.log(res)
return res.length;
}
console.log(generateDistinctString('aab', 2));
如果字符已经被使用或者与current的最后一个字符相同则跳过。