๐ 22. ๆฌๅท็ๆ
2022ๅนด6ๆ20ๆฅ
- algorithm
๐ 22. ๆฌๅท็ๆ
้พๅบฆ: ๐
้ฎ้ขๆ่ฟฐ
่งฃๆณ
class Solution {
List<String> res = new ArrayList<>();
public List<String> generateParenthesis(int n) {
// ๆ่ทฏ๏ผ
// ็ฑปไผผไบๅๆ
StringBuilder sb = new StringBuilder();
mySol(n, 0, 0, sb);
return res;
}
private void mySol(int n, int left, int right, StringBuilder sb) {
// ้ๅฝ็ปๆญขๆกไปถ
if(left < right) {
return;
}
if(left == n && right == n) {
res.add(sb.toString());
return;
}
if(left < n) {
sb.append("(");
mySol(n, left + 1, right, sb);
sb.deleteCharAt(sb.length() - 1);
}
if(left > right) {
sb.append(")");
mySol(n, left, right + 1, sb);
sb.deleteCharAt(sb.length() - 1);
}
}
}