Java solution


  • 0
    O
    class Solution {
        /**
         * Generate combinations.
         *
         * @param result result list.
         * @param pref current prefix.
         * @param open parentheses that can be opened.
         * @param close parentheses that needs to be closed.
         */
        public void combination(List<String> result, String prefix, int open, int close) {
            // If cannot open or close then we are done
            if (open == 0 && close == 0) {
                result.add(prefix);
            } else {
                // If can open parentheses generate combinations from it
                if (open > 0) {
                    combination(result, prefix + '(', open - 1, close + 1);
                }
                
                // If can close parentheses generate combinations from it
                if (close > 0) {
                    combination(result, prefix + ')', open, close - 1);
                }
            }
        }
        
        public List<String> generateParenthesis(int n) {
            List<String> result = new LinkedList<>();
            
            // Generate combinations of opening n parantheses
            combination(result, "", n, 0);
            
            return result;
        }
    }
    

Log in to reply
 

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