LeetCode 022 Generate Parentheses

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:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

Topic Analysis and Implementation

The most basic way is to use a recursive method, a full permutation of all possible situations, and the determination for each qualified queued.
Determining whether a qualified manner, setting the value of temp == 0, +1 met left parenthesis, right parenthesis minus one. If the case appeared in the middle of the temp is less than 0, that is unacceptable. Finally temp appear not equal to 0, then also failed.

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> combinations = new ArrayList();
        char current [] = new char[2*n];
        generateALL(current,0,combinations);
        return combinations;
    }
    public void generateALL(char []current,int pos,List<String> list){
        if(pos == current.length){
            if(valid(current))
                list.add(new String (current));
        }else{
             current[pos] = '(';
             generateALL(current,pos+1,list);
             current[pos] = ')';
             generateALL(current,pos+1,list);
        }      
    }
    public boolean valid(char []a){
        int temp = 0;//个数
        for(char x : a){
            if(temp < 0)
                return false;
            if(x == '(')
                temp++;
            else
                temp--;
        }
        return (temp == 0);

    }
}

Here Insert Picture DescriptionThen say the following to improve performance, emmmmm, did not understand. . . . Simply getting in on this I would utilize it.

Guess you like

Origin blog.csdn.net/qunqunstyle99/article/details/94205146