方法一:生成一个树然后打印每条从根节点到叶节点的路径,其实比较麻烦。打印的时候需要判断叶节点是不是左括号
//define left parenthesis as -1, right parenthesis as 1
class Solution {
public:
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
};
void generateTree(TreeNode* root, int parenthesis, int left,int right)
{
root->val = parenthesis;
root->left = NULL;
root->right = NULL;
if (left > 0)
{
int templeft = left - 1;
root->left = new TreeNode;
generateTree(root->left, -1,templeft,right);
}
if (right > 0&&(right-1>=left))
{
int tempright = right - 1;
root->right = new TreeNode;
generateTree(root->right, 1, left, tempright);
}
}
string int2Parenthesis(int val)
{
if (val == -1)
return "(";
if (val == 1)
return ")";
}
//打印根节点到叶子节点
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> ans;
if (root == nullptr) return ans;
queue<TreeNode*> q1;//用于层序遍历
queue<string> q2;//用于存储路径
TreeNode* T = root;
string cur;
cur = int2Parenthesis(T->val);
q1.push(T);
q2.push(cur);
while (!q1.empty())
{
T = q1.front();
q1.pop();
if (T->left || T->right)
{
cur = q2.front();
if (T->left)
{
q1.push(T->left);
q2.push(cur + int2Parenthesis((T->left)->val));
}
if (T->right)
{
q1.push(T->right);
q2.push(cur + int2Parenthesis((T->right)->val));
}
q2.pop();
}
else//叶子节点弹出
{
string tempPath = q2.front();
if (tempPath.back() == ')')
{
ans.push_back(q2.front());
}
q2.pop();
}
}
return ans;
}
vector<string> generateParenthesis(int n) {
TreeNode* root = new TreeNode;
generateTree(root, -1, n-1, n);
vector<string> ans;
ans = binaryTreePaths(root);
return ans;
}
};
方法二:回溯法。其实括号的生成过程只需要控制")“的数量小于等于”("的数量即可。递归中每次return之后回到外一层函数,下一步进行pop_back,则可腾出string末尾的括号位置,移至下一个分支。相当于实现了方法一中树的结构
using namespace std;
class Solution {
public:
void backTrack(vector<string>& result, string & current, int open, int close, int n)
{
if (current.size() == n * 2)
{
result.push_back(current);
return;
}
if (open < n)
{
current.append("(");
backTrack(result, current, open + 1, close, n);
current.pop_back();
}
if (close < open)
{
current.append(")");
backTrack(result, current, open, close + 1, n);
current.pop_back();
}
}
vector<string> generateParenthesis(int n) {
vector<string> ans;
string cur;
backTrack(ans, cur, 0, 0, n);
return ans;
}
};