-
-
Notifications
You must be signed in to change notification settings - Fork 243
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
求集合单词组合起来的不同结果,集合中的单词不重复,每个结果包含所有单词 #418
Comments
const arr = ["a","b","c","d","e"];
// 回溯算法
function main(arr){
if(arr.length === 1) return [arr[0]];
let res = [];
for(let i = 0; i < arr.length; ++i){
const newArray = [...arr.slice(0, i),...arr.slice(i + 1)];
res = res.concat(main(newArray).map(item => arr[i] + item));
}
return res;
}
// 5! = 120,正解
console.log(new Set(main(arr)).size) |
|
非递归方法 function main(arr) {
if (!arr.length) return []
let res = [arr[0]]
for (let i = 1; i < arr.length; i++) {
let temp = []
for (const item of res) {
for (let x = 0; x <= item.length; x++) {
temp.push(item.slice(0, x) + arr[i] + item.slice(x))
}
}
res = temp
}
return res
} |
回溯算法
// 求集合单词组合起来的不同结果,集合中的单词不重复,每个结果包含所有单词
function permute2(arr) {
let path = [];
let restult = [];
function DFS(index) {
if (path.length === arr.length) {
restult.push([...path]);
return;
}
for (let i = 0; i < arr.length; i++) {
if (path.includes(arr[i])) {
continue;
}
path.push(arr[i]);
DFS(index + 1);
path.pop();
}
}
DFS(0);
console.log(restult);
}
permute2(["a", "b", "c", "d", "e"]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: