您的位置:首页 > 其它

22. Generate Parentheses

2015-07-02 22:17 369 查看
这道题目,我是通过DFS来做的,但是为了判断由N个“(”和N个")"生成的字符串是否合法,于是我又写了个函数ifNormal。ifNormal函数的复杂度为为O(N)。而实际上,根本不需要另外写ifNormal函数。那怎么判断生成的字符串是否合法,或者从在程序逻辑上根本不允许生成那些不合法的字符串呢?答案就是在DFS的时候,如果"("的数量小于N,那么就可以继续放"(",如果")"的数量小于"("的数量,也可以选择放")"。为什么")"的数量要小于"("的数量才能选择放")"呢?因为"("和")"是成对的,任何一个")"在前面都必有一个相应的"("。所以只有当")"的数量小于"("的数量时,才可以选择放")"。我原来的代码如下:

bool ifNormal(string& item) {
stack<char> seq;
for (int i=0; i<item.size(); i++) {
if (item[i] == '(') {
seq.push(item[i]);
} else if (seq.empty()  ){
return false;
} else {
char c = seq.top();
seq.pop();
if (c != '(') {
return false;
}
}
}
return seq.empty();
}
void getParenthesis(vector<string>& result, string& subItem, int leftRemain, int rightRemain) {
if (leftRemain == 0 && rightRemain == 0) {
string item = "(" + subItem + ")";
if (ifNormal(item)) {
result.push_back(item);
}
return;
}
if (leftRemain != 0) {
subItem += "(";
getParenthesis(result, subItem, leftRemain-1, rightRemain);
subItem.pop_back();
}
if (rightRemain != 0) {
subItem += ")";
getParenthesis(result, subItem, leftRemain, rightRemain-1);
subItem.pop_back();
}

}
vector<string> generateParenthesis(int n) {
vector<string> result;
string subItem;
getParenthesis(result, subItem, n-1, n-1);
return result;
}


修改后的代码如下:

vector<string> generateParenthesis(int n) {
vector<string> result;
string item;
dfs(result, item, n, n);
return result;
}
<span style="color:#ff0000;">    /*
left and right represents the remaining number of ( and ) that need to be added.
When left > right, there are more ")" placed than "(". Such cases are wrong and the method stops.
*/
</span>    void dfs(vector<string>& result, string& item, int left, int right){
if(left > right)
return;

if(left==0 && right==0){
result.push_back(item);
return;
}

string tmp;
if(left>0){
tmp = item + "(";
dfs(result, tmp, left-1, right);
}

if(right>0){
tmp = item + ")";
dfs(result, tmp, left, right-1);
}
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: