Leetcode22 Generate Parentheses
这题沿着思路就想到了递归,但是自己总结的规律并不对,所以到后面就会少。
参考Discuss:
import java.util.ArrayList;
import java.util.List;
public class GenerateParenthesis22 {
public List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList<String>();
helper(ans,"",0,0,n);
return ans;
}
private void helper(List<String> ans,String str,int open,int close,int max) {
if(str.length()==2*max) {
ans.add(str);
return;
}
if(open<max) {
helper(ans,str+'(',open+1,close,max);
}
if(close<open) {
helper(ans,str+')',open,close+1,max);
}
}
}
2ms,基本在最快行列了,把str改成StringBuilder,重复利用,注意每次重新作为参数的时候去掉上次加入的数据,即可beat100%。
helper(n, result, runStr, open+1, close);
runStr.deleteCharAt(runStr.length()-1);

浙公网安备 33010602011771号