427. Generate Parentheses
Given n, and there are n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example
Example 1:
Input: 3
Output: ["((()))", "(()())", "(())()", "()(())", "()()()"]
Example 2:
Input: 2
Output: ["()()", "(())"]
Input test data (one parameter per line)How to understand a testcase?
解法1:感觉这题其实不容易,关键是要做到不TLE思路要比较巧妙才行,所以重点在于剪枝。
1) 首先我们要知道什么样的表达式才是合法的。其实就是从头往后数,如果在某一位置的累积右括号数多于累积左括号数,那么就不合法。否则就合法。
2) 把当前累计左括号数和累计右括号数都放到入口参数,方便剪枝。不然要再写一个函数parse sol,会浪费时间!
3) dfs里面分几种情况处理:
case 1: left == n && right == n,此时sol一定合法,存下来退出即可。
case 2: left == n,此时right一定<n,此时sol的剩余字符只能都是')'了,补全就是。
那么有人可能会问,会不会出现right>left的情况呢?照代码中4种case来的话就不会。
case 3: left < n && left > right,此时分2种情况处理,一个是加一个'(’,一个是加一个')',分别调用dfs即可。
case 4: left < n && left == right,此时只可能加一个'(',调用dfs。
class Solution {
public:
/**
* @param n: n pairs
* @return: All combinations of well-formed parentheses
*/
vector<string> generateParenthesis(int n) {
string sol = "";
vector<string> sols;
dfs(n, 0, 0, sols, sol);
return sols;
}
private:
void dfs(int n, int left, int right, vector<string> & sols, string sol) {
if (left == n && right == n) {
sols.push_back(sol);
return;
}
if (left == n) {
sol += string(n - right, ')');
sols.push_back(sol);
return;
} else if (left > right) {
dfs(n, left + 1, right, sols, sol + '(');
dfs(n, left, right + 1, sols, sol + ')');
} else if (left == right) {
dfs(n, left + 1, right, sols, sol + '(');
}
}
};
我之前的代码如下,代码应该理论上没错,但当n稍微大一点就会超时。关键是剪枝没处理后,还专门编写一些函数来剪枝,浪费时间。
class Solution {
public:
/**
* @param n: n pairs
* @return: All combinations of well-formed parentheses
*/
vector<string> generateParenthesis(int n) {
string sol = "";
set<string> sols;
dfs(2 * n, 0, sols, sol);
vector<string> result(sols.begin(), sols.end());
return result;
}
private:
bool validParenthesis(string &sol) {
stack<char> s;
int n = sol.size();
for (int i = 0; i < n; ++i) {
if (sol[i] == '(') s.push(sol[i]);
else if (sol[i] == ')') {
if (s.empty()) return false;
s.pop();
}
}
if (!s.empty()) return false;
return true;
}
void dfs(int n, int pos, set<string> & sols, string & sol) {
if (pos == n) {
if (validParenthesis(sol)) {
sols.insert(sol);
}
return;
}
for (int i = pos; i < n; ++i) {
sol.push_back('(');
dfs(n, pos + 1, sols, sol);
sol.pop_back();
sol.push_back(')');
dfs(n, pos + 1, sols, sol);
sol.pop_back();
}
}
};
二刷:
class Solution {
public:
/**
* @param n: n pairs
* @return: All combinations of well-formed parentheses
* we will sort your return value in output
*/
vector<string> generateParenthesis(int n) {
if (n == 0) return {};
string sol;
vector<string> sols;
helper(n, sol, sols, 0, 0);
return sols;
}
private:
void helper(int n, string &sol, vector<string> &sols, int leftCount, int rightCount) {
if (leftCount == n && rightCount == n) {
sols.push_back(sol);
return;
}
if (leftCount == n) {
sol = sol + ")";
helper(n, sol, sols, leftCount, rightCount + 1);
sol.pop_back();
return;
}
if (leftCount > rightCount) {
sol = sol + "(";
helper(n, sol, sols, leftCount + 1, rightCount);
sol.pop_back();
sol = sol + ")";
helper(n, sol, sols, leftCount, rightCount + 1);
sol.pop_back();
}
if (leftCount == rightCount) {
sol = sol + "(";
helper(n, sol, sols, leftCount + 1, rightCount);
sol.pop_back();
return;
}
}
};
解法2:在网上看到的,感觉非常不错。
思路就是找左括号,每找到一个左括号,就在其后面加一个完整的括号,最后在开头加一个 ()。用set来去重。
为什么这个方法可行呢?
以n=3为例,我们来看debug的输出就可以理解了。
n=1 a=
insert ()
n=2 a=()
insert (())
insert ()()
n=3 a=()()
insert (())()
insert ()(())
insert ()()()
n=3 a=(())
insert (()())
insert ((()))
insert ()(())
Output
["((()))","(()())","(())()","()(())","()()()"]
class Solution {
public:
vector<string> generateParenthesis(int n) {
unordered_set<string> st;
if (n == 0) return {""};
else {
vector<string> pre = generateParenthesis(n - 1);
for (auto a : pre) {
cout<<" n="<<n<<" a="<<a<<endl;
for (int i = 0; i < a.size(); ++i) {
if (a[i] == '(') {
a.insert(a.begin() + i + 1, '(');
a.insert(a.begin() + i + 2, ')');
st.insert(a);
cout<<" insert "<<a<<endl;
a.erase(a.begin() + i + 1, a.begin() + i + 3);
}
}
st.insert("()" + a);
cout<<" insert "<<"()" + a<<endl;
}
}
return vector<string>(st.begin(), st.end());
}
};