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

来源:互联网 发布:java全排列 编辑:程序博客网 时间:2024/06/07 08:38

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)


0 0