全排列功能
分解成多个子问题就行
// 递归
const fullPermutate = (str) => {
const result = [];
if (str.length > 1) {
for (let i = 0; i < str.length; i += 1) {
const cur = str[i];
// 获取下一部分的字符串
const restArr = str.slice(0, i) + str.slice(i + 1, str.length);
// 将两者组合起来
const subResult = fullPermutate(restArr);
for (let j = 0; j < subResult.length; j += 1) {
result.push(cur + subResult[j]);
}
}
} else {
result.push(str);
}
return result;
};
fullPermutate('abc');
// 回溯
const full = (str1) => {
const result = [];
const hs = (str, path) => {
if (str.length === 0) {
result.push(path.join(''));
} else {
for (let i = 0; i < str.length; i += 1) {
path.push(str[i]);
const tempStr = str.slice(0, i) + str.slice(i + 1);
hs(tempStr, path);
// 还原path
path.pop();
}
}
};
hs(str1, []);
console.log(result);
};
full('abcde');