Leetcode 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:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

s思路:
1. backtraking. 在每一个位置处,我们都记录目前有多少个左括号和右括号,如果左括号不足n个,就继续添加左括号;另外一种选择是,如果右括号的个数少于做括号,也可以添加右括号。注意:以上两种情况都需要判断执行。
2. 这道题是如何用数学或程序语言来模拟问题的呢?大框架肯定是backtracking,然后需要两个变量来统计左右括号的数量,根据括号的数量来做不同的操作!

//方法1:backtracking.和普通的for+backtracking不同在于,
//两种情况都列举出来了,所以不用for循环了,但仍然是backtrakcing
class Solution {
public:

    void helper(vector<string>& res, string cur,int n,int left,int right){
        if(left==n&&right==n){
            res.push_back(cur);
            return; 
        }
        //for(int i=left;i
        //注意:不是所有的backtracking都需要for+recursive
        if(left'(',n,left+1,right);
        }
        //for(int i=right;i
        //注意:不是所有的backtracking都需要for+recursive
        if(right')',n,left,right+1);
        }
    }

    vector<string> generateParenthesis(int n) {
        //
        vector<string> res;
        helper(res,"",n,0,0);
        return res;
    }
};

你可能感兴趣的:(leetcode,backtrack)