My 2ms backtracking java solution using StringBuilder


  • 0
    G

    My 2ms backtracking java solution using StringBuilder

    public class Solution {
        public List<String> generateParenthesis(int n) {
            List<String> res = new ArrayList<>();
            helper(new StringBuilder(), 0, n, res);
            return res;
        }
        
        private void helper(StringBuilder pre, int score, int n, List<String> res){
            if(pre.length() == 2 * n){
                if(score == 0) res.add(pre.toString());
                return;
            }
            if(2*n - pre.length() < score) return;
            if(score != 0) {
                helper(pre.append(")"), score-1, n, res);
                pre.deleteCharAt(pre.length()-1);
            }
            if(score != n && 2*n - pre.length() > score) {
                helper(pre.append("("), score+1, n, res);
                pre.deleteCharAt(pre.length()-1);
            }
        }
    }
    

Log in to reply
 

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