标签:void color 代码 ring parent vector public output 退出
问题:
给定一个计量括号数量的数字n,求所有的括号组合可能序列。
Example 1: Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"] Example 2: Input: n = 1 Output: ["()"] Constraints: 1 <= n <= 8
解法:Backtracking(回溯算法)
参数:
处理:
代码参考:
1 class Solution { 2 public: 3 vector<string> generateParenthesis(int n) { 4 vector<string> res; 5 backtracking(res, "", n, n); 6 return res; 7 } 8 void backtracking(vector<string>& res, string path, int optionlist, int optend) { 9 if(optionlist == 0) { 10 while(optend){ 11 path+=‘)‘; 12 optend--; 13 } 14 res.push_back(path); 15 return; 16 } 17 backtracking(res, path+‘(‘, optionlist-1, optend); 18 if(optend <= optionlist) return;//‘(‘ must before ‘)‘ 19 backtracking(res, path+‘)‘, optionlist, optend-1); 20 return; 21 } 22 };
标签:void color 代码 ring parent vector public output 退出
原文地址:https://www.cnblogs.com/habibah-chang/p/14222511.html