Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Javascript

ทุกวิธีในการปรับสมดุล n วงเล็บใน JavaScript


ปัญหา

เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่มีตัวเลข n ฟังก์ชันของเราควรส่งคืนอาร์เรย์ที่แสดงวิธีการปรับสมดุล 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);

ผลลัพธ์

ต่อไปนี้เป็นเอาต์พุตคอนโซล -

[ '((()))', '(()())', '(())()', '()(())', '()()()' ]