[LeetCode]022. Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"

Solution: 

use recursion, 

when the numbers of '(' less than n, append '(';

when the numbers of ')' less than '(', append ')';

don't forget delete the last char in the sb(string buffer) after each recursion.

套用的letter combinations of phone number那题的思路来解的,对两个if语句的顺序还有每次删除最后一个字符还是有些不清楚。


public class Solution {
    public ArrayList<String> generateParenthesis(int n) {
        // Start typing your Java solution below
        // DO NOT write main() function
        ArrayList<String> list = new ArrayList<String>();
        StringBuffer sb = new StringBuffer();
        if(n <= 0){
            return list;
        }
        generateP(list, sb, n, 0, 0, 0);
        return list;
        
    }
    
    public void generateP(ArrayList<String> list, StringBuffer sb, int n, int leftP, int rightP, int index){
        if(index == 2*n){
            list.add(sb.toString());
        }
        if(leftP < n){
            sb.append('(');
            generateP(list, sb, n, leftP+1, rightP, index+1);
            sb.deleteCharAt(sb.length()-1);
        }
        if(rightP < leftP){
            sb.append(')');
            generateP(list, sb, n, leftP, rightP+1, index+1);
            sb.deleteCharAt(sb.length()-1);
        }
    }
}


你可能感兴趣的:(LeetCode,recursion)