JAVA DFS Solution beat 99.77%


  • 0

    Use DFS to generate each condition

    public class Solution {
        public List<String> generateParenthesis(int n) {
            List<String> result = new ArrayList<>();
            char [] cur = new char [n*2];
            helper(cur,n,n,0,result);
            return result;
        }
        private void helper(char [] cur, int right, int left, int index, List<String> result){
            if(left==0 && right == 0){
                result.add(new String(cur));
            }
            if(left>0){
                cur[index]='(';
                helper(cur,right,left-1,index+1,result);
            }
            if(right>left){
                cur[index]=')';
                helper(cur,right-1,left,index+1,result);
            }
        }
    }

Log in to reply
 

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