-
-
Notifications
You must be signed in to change notification settings - Fork 235
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
多维数组全排列 #81
Comments
function permute(arr) {
if (arr.length === 1) return arr[0];
let result = [];
for (let i = 0; i < arr.length; i++) {
let restArr = [...arr.slice(0, i), ...arr.slice(i + 1)];
for(let sub of permute(restArr)) {
result.push([arr[i], ...sub]);
}
}
return result;
}
let testArr = [[1,2],[3,4],[5,6]];
console.log(permute(testArr));
// 输出:[[1,3,5],[1,3,6],[1,4,5],[1,4,6],[2 ,3 ,5] ,[2 ,3 ,6] ,[2 ,4 ,5] ,[2 ,4 ,6]]
function generateCombinations(arr) {
return arr.reduce((acc, val) => {
return acc.map(v => val.map(item => [...v, item])).flat();
}, [[]]);
}
let testArr = [[1, 2], [3, 4], [5, 6]];
console.log(generateCombinations(testArr));
// 输出:[[1 ,3 ,5] ,[1 ,3 ,6] ,[1 ,4 ,5] ,[1 ,4 ,6] ,[2 ,3 ,5] ,[2 ,3 ,6] ,[2 ,4 ,5],[2,4,6]] |
思路:先两两结合,得到结果再跟后面的结合。
|
// 回溯
|
// 回溯算法
function permute(arr) {
let path = [];
let result = [];
let n = arr.length;
function DFS(index) {
if (path.length === n) {
result.push([...path]);
return;
}
for (let i = 0; i < arr.length - 1; i++) {
path.push(arr[index][i]);
DFS(index + 1);
path.pop();
}
}
DFS(0);
return result;
}
let testArr = [
[1, 2],
[3, 4],
[5, 6],
];
console.log(permute(testArr)); |
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: