เราได้รับอาร์เรย์ของจำนวนเต็มที่ไม่ซ้ำกัน และต้องคืน permutations ทั้งหมดของจำนวนเต็มในอาร์เรย์
ตัวอย่าง: ถ้าอินพุตอาร์เรย์คือ:
const arr = [1, 2, 3];
ผลลัพธ์ควรเป็น:
const output = [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ];
ตัวอย่างโค้ด
const arr = [1, 2, 3];
const findPermutations = (arr = []) => {
let res = []
const helper = (arr2) => {
if (arr2.length==arr.length)
return res.push(arr2)
for(let e of arr)
if (!arr2.includes(e))
helper([...arr2, e])
};
helper([])
return res;
};
console.log(findPermutations(arr));
ผลลัพธ์
ผลลัพธ์ที่แสดงในคอนโซลจะเป็นดังนี้:
[ [ 1, 2, 3 ], [ 1, 3, 2 ], [ 2, 1, 3 ], [ 2, 3, 1 ], [ 3, 1, 2 ], [ 3, 2, 1 ] ]