java recursion solution


  • 0

    use an int as a flag,
    '(' , +1
    ')', -1
    when the flag is 0, only "(" is allowed.

    public class Solution {
        public List<String> generateParenthesis(int n) {
            List<String> r = new ArrayList<String>();
            char[] s = new char[2*n];
            gen(r, 0, 0, n, n, s);
            return r;
        }
        
        public void gen(List<String> result, int index, int s, int nl, int nr, char[] temp) {
            if(nl == 0 && nr == 0) {
                result.add(new String(temp));
                return;
            }
            
            if(nl > 0){
                temp[index] = '(';
                gen(result, index+1, s+1, nl-1, nr, temp);
            }
            
            if(s > 0 && nr > 0) {
                temp[index] = ')';
                gen(result, index+1, s-1, nl, nr-1, temp);
            }
        }
    }
    

Log in to reply
 

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