Java concise Backtracking solution


  • 0
    P
    public class Solution {
        public List<String> generateParenthesis(int n) {
            List<String> ret = new ArrayList<String>();
            StringBuffer sb = new StringBuffer();
            int left=n;
            int right=n;
            dfs(ret,sb,n,n);
            return ret;
        }
        
        public void dfs(List<String> ret, StringBuffer sb, int left, int right){
            if(left>right){
                return;
            }
            if(right==0){
                ret.add(sb.toString());
            }else{
                if(left>0){
                    sb.append('(');
                    dfs(ret,sb,left-1,right);
                    sb.deleteCharAt(sb.length()-1);
                }
                sb.append(')');
                dfs(ret,sb,left,right-1);
                sb.deleteCharAt(sb.length()-1);
            }
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.