ภาพรวม
เราต้องเขียนฟังก์ชันที่:
- รับอาร์เรย์จำนวนเต็ม (เช่น [1,2,3,4])
- สร้างอาร์เรย์ของทุก Permutation ของ [1,2,3,4] โดยแต่ละ permutation มีความยาว 4 (เท่ากับอาร์เรย์ต้นฉบับ)
ตัวอย่างโค้ด
const arr = [1, 2, 3, 4];
const permute = (arr = [], res = [], used = []) => {
let i, ch;
for (i = 0; i < arr.length; i++) {
ch = arr.splice(i, 1)[0];
used.push(ch);
if (arr.length === 0) {
res.push(used.slice());
}
permute(arr, res, used);
arr.splice(i, 0, ch);
used.pop();
}
return res;
};
console.log(permute(arr));
ผลลัพธ์ในคอนโซล
[
[ 1, 2, 3, 4 ], [ 1, 2, 4, 3 ],
[ 1, 3, 2, 4 ], [ 1, 3, 4, 2 ],
[ 1, 4, 2, 3 ], [ 1, 4, 3, 2 ],
[ 2, 1, 3, 4 ], [ 2, 1, 4, 3 ],
[ 2, 3, 1, 4 ], [ 2, 3, 4, 1 ],
[ 2, 4, 1, 3 ], [ 2, 4, 3, 1 ],
[ 3, 1, 2, 4 ], [ 3, 1, 4, 2 ],
[ 3, 2, 1, 4 ], [ 3, 2, 4, 1 ],
[ 3, 4, 1, 2 ], [ 3, 4, 2, 1 ],
[ 4, 1, 2, 3 ], [ 4, 1, 3, 2 ],
[ 4, 2, 1, 3 ], [ 4, 2, 3, 1 ],
[ 4, 3, 1, 2 ], [ 4, 3, 2, 1 ]
]