22. Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
题意:求n双括号的所有有效组合
代码如下:
/** * @param {number} n * @return {string[]} 回溯 */ var generateParenthesis = function(n) { var res=[]; back(res,"",0,0,n); return res; }; //list :结果数组 //str :收集结果的某一项 //left:左括号 //right:右括号 //n:括号对数 function back(list,str,left,right,n){ if(str.length==2*n){ list.push(str); return ; } if(left<n) back(list,str+"(",left+1,right,n); if(left>right) back(list,str+")",left,right+1,n); }