我尝试解决这个leetcode 22问题:给定数字n,生成括号。我知道还有其他方法可以解决这个问题;我只想知道为什么我的算法在数学上不起作用。
我试图通过将左开括号放置在每个有效位置,并通过将其与右括号交换,直到字符串
((()))
变为()()()
来解决它。它对于小于等于3的数字有效,但对于大于3的数字无效。vector<string> generateParenthesis(int n) {
vector<string> fin;
string baseString = "";
for(int i = 0; i < n; i++) {
baseString = "(" + baseString + ")";
}
fin.push_back(baseString);
for(int l = n - 1; l > 0; l--) {
int r = n;
while (r < baseString.size() - 1) {
// cout << "something";
string cst = baseString;
char temp = cst[r];
cst[r] = cst[l];
cst[l] = temp;
r++;
fin.push_back(cst);
}
}
return fin;
}
有人能解释一下为什么它不能生成所有的组合,以及是否可以扩展它来实现这一点吗?