JAVA Solution


  • 0
    Y
    public class Solution {
        public List<String> generateParenthesis(int n) {
            List<String> res = new ArrayList<String>();
            getRes(n, 0, 0, res, "", 0);
            return res;
        }
        
        public void getRes(int n, int cur, int len, List<String> res, String s, int balance){
            if(cur > n || len > 2 *n)
                return;
            if(cur == n && s.length() == 2 * n && balance == 0){
                res.add(s);
                return;
            }
            getRes(n, cur + 1, len + 1, res, s + "(", balance + 1);
            if(balance > 0)
                getRes(n, cur, len + 1, res, s + ")", balance - 1);
        }
    }

  • 0
    F

    beautiful!!!!!!!


Log in to reply
 

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