标签:tor generate 就是 ati 回溯法 选项 算法 == nat
算法描述:
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,同时右括号数量不能大于左括号。
vector<string> generateParenthesis(int n) { vector<string> results; generate(results, "", 0,0,n); return results; } void generate(vector<string>& results, string curr, int left, int right, int n){ if(curr.size() == 2*n){ results.push_back(curr); return; } string tmp = ""; if(left < n){ tmp = curr +"("; generate(results,tmp, left+1, right, n); } if(right < left){ tmp = curr + ")"; generate(results,tmp, left, right+1,n); } }
LeetCode-22-Generate Parentheses
标签:tor generate 就是 ati 回溯法 选项 算法 == nat
原文地址:https://www.cnblogs.com/nobodywang/p/10319074.html