1. 程式人生 > >LeetCode 22 Generate Parentheses (C,C++,Java,Python)

LeetCode 22 Generate Parentheses (C,C++,Java,Python)

Problem:

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:

遞迴遍歷即可,注意兩個條件,要插入‘(’的時候一定要剩餘的數目大於0,要插入‘)’的時候一定要剩餘的數目大於0 並且剩餘的)的數目大於剩餘的( 的數目

題目大意:

給一個數目n要求組合成一個由n個括號組成的字串,要求輸出所有的可能排列情況。

Java原始碼(252ms):

public class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<String>();
        char[] tmp=new char[n+n];
        generate(res,n,n,tmp,0);
        return res;
    }
    private void generate(List<String> res,int l,int r,char[] tmp,int index){
        if(l==0 && r==0){
            res.add(new String(tmp));
            return;
        }
        if(l>0){
            tmp[index]='(';
            generate(res,l-1,r,tmp,index+1);
        }
        if(r>0 && r>l){
            tmp[index]=')';
            generate(res,l,r-1,tmp,index+1);
        }
    }
}

C語言原始碼(2ms):

void generate(char** res,int* size,int l,int r,char* tmp,int index){
    if(l==0 && r==0){
        tmp[index]=0;
        res[*size]=(char*)malloc(sizeof(char)*index);
        strcpy(res[*size],tmp);
        (*size)++;
        return;
    }
    if(l>0){
        tmp[index]='(';
        generate(res,size,l-1,r,tmp,index+1);
    }
    if(r>0 && l<r){
        tmp[index]=')';
        generate(res,size,l,r-1,tmp,index+1);
    }
}
char** generateParenthesis(int n, int* returnSize) {
    char** res;
    char* tmp=(char*)malloc(sizeof(char)*(n*2+1));
    int l=n,r=n;
    res=(char**)malloc(sizeof(char*)*1000000);
    *returnSize=0;
    generate(res,returnSize,l,r,tmp,0);
    return res;
}

C++原始碼(4ms):

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> res;
        char* tmp=(char*)malloc(sizeof(char)*(n+n+1));
        generate(res,n,n,tmp,0);
        return res;
    }
private:
    void generate(vector<string>& res,int l,int r,char* tmp,int index){
        if(l==0 && r==0){
            tmp[index]=0;
            res.push_back(string(tmp));
            return;
        }
        if(l>0){
            tmp[index]='(';
            generate(res,l-1,r,tmp,index+1);
        }
        if(r>0 && r>l){
            tmp[index]=')';
            generate(res,l,r-1,tmp,index+1);
        }
    }
};

Python原始碼(57ms):

class Solution:
    # @param {integer} n
    # @return {string[]}
    def generateParenthesis(self, n):
        res=[]
        tmp=['' for i in range(n+n)]
        self.generate(res,n,n,tmp,0)
        return res
    def generate(self,res,l,r,tmp,index):
        if l==0 and r==0:
            res.append(''.join(tmp))
            return
        if l>0:
            tmp[index]='('
            self.generate(res,l-1,r,tmp,index+1)
        if r>0 and r>l:
            tmp[index]=')'
            self.generate(res,l,r-1,tmp,index+1)