回溯的本质是穷举,穷举所有情况,这里有剪枝,只在有效情况下继续
class Solution { vector<string> res; string str; void backtracking(int left,int right){ if(left<0 || left>right) return;//出现无效情况就不继续 if(left==0 && right==0){ res.emplace_back(str); return; } if(left>0){//只在有效情况下继续 str+='('; backtracking(left-1,right); str.pop_back(); } if(right>left){ str+=')'; backtracking(left,right-1); str.pop_back(); } } public: vector<string> generateParenthesis(int n) { res.clear(); str.clear(); backtracking(n,n); return res; } };
标签:right,int,res,生成,括号,str,leetcode,backtracking,left From: https://www.cnblogs.com/lcstudy2021/p/17609729.html