ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับตัวเลข n ฟังก์ชันควรคืนค่าอาร์เรย์ที่แสดงวิธีการจัดวงเล็บให้สมดุล (balanced parentheses) ทั้งหมดของ n คู่
เช่น สำหรับ n = 3 เอาต์พุทจะเป็น:
["()()()","(())()","()(())","(()())","((()))"]
ตัวอย่าง
โค้ดตัวอย่างดังนี้:
const res = [];
const buildcombination = (left, right, str) => {
if (left === 0 && right === 0) {
res.push(str);
}
if (left > 0) {
buildcombination(left-1, right+1, str+"(");
}
if (right > 0) {
buildcombination(left, right-1, str+")");
}
}
buildcombination(3, 0, "");
console.log(res);
ผลลัพธ์
ผลลัพธ์ในคอนโซล:
[ '((()))', '(()())', '(())()', '()(())', '()()()' ]