22 Generate Parentheses
阿新 • • 發佈:2018-11-25
遞迴然後剪枝 其實相當於dfs的思想 (我感覺的,因為也是一條路走到黑然後去重)
思路:一開始把’(‘和’)'分列兩旁 然後開始交換 '(‘只能和’)'交換,然後check檢查兩個情況
1.重複 2.括號不正確
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string>ans;
string str;
//ini
for (int i = 0; i < n; ++i)str += '(';
for (int i = 0; i < n; ++i)str += ')';
ans.push_back(str);
generateParenthesis_Recursive(ans, str);
return ans;
}
bool check(vector<string>& ans, string str) {
//ditto
for (int i = 0; i < ans.size(); ++i)if (ans[i] == str)return false;
//correctness
int Cnt = 0;
for (int i = 0; i < str. size(); ++i) {
if (str[i] == '(')++Cnt;
else if (str[i] == ')') {
if (Cnt == 0)return false;
else --Cnt;
}
}
return true;
}
void swap_str(string& str, int i, int j) {
char t = str[i];
str[i] = str[j];
str[j] = t;
}
void generateParenthesis_Recursive(vector<string> & ans,string str) {
for (int i = 0; i < str.size(); ++i) {
for (int j = i + 1; j < str.size(); ++j) {
if (str[i] == str[j])continue;
swap_str(str, i, j);
if (check(ans, str)){
ans.push_back(str);
generateParenthesis_Recursive(ans, str);
}
swap_str(str, j, i);
}
}
}
};