Leetcode 22) Generate Parentheses
in Algorithms
내 답안
class Solution {
public List<String> generateParenthesis(int n) {
return recursive(0,n);
}
public List<String> recursive(int close, int left){
List<String> cur = new ArrayList<>();
if(close ==0 && left==0){
cur.add("");
return cur;
}
List<String> prev;
if(left!=0){
prev =recursive(close+1,left-1);
for(String i : prev ){
cur.add("("+i);
}
if(close==0){
return cur;
}
}
prev =recursive(close-1,left);
for(String i : prev ){
cur.add(")"+i);
}
return cur;
}
}
다른 답안
class Solution {
//O(n) space, O 4 to power n
public List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList();
backtrack(ans, new StringBuilder(), 0, 0, n);
return ans;
}
public void backtrack(List<String> ans, StringBuilder cur, int open, int close, int max){
if (cur.length() == max * 2) {
ans.add(cur.toString());
return;
}
if (open < max) {
cur.append("(");
backtrack(ans, cur, open+1, close, max);
cur.deleteCharAt(cur.length() - 1);
}
if (close < open) {
cur.append(")");
backtrack(ans, cur, open, close+1, max);
cur.deleteCharAt(cur.length() - 1);
}
}
}
오답
- cur.add(“”); 이걸 안해줘서 null이 됐고, 다음 loop문들 다 못돌아서 null값 뜸!
public List<String> recursive(int close, int left){
List<String> cur = new ArrayList<>();
if(close ==0 && left==0){
//cur.add("");
return cur;
}