leetcode第22题——**Generate Parentheses

25 篇文章 0 订阅
25 篇文章 0 订阅

题目

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:

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

思路

题目要求是给出一个数字n,要将n对括号可能形成的合法字符串存在一个列表里并返回这个列表,例如n=2则函数应该返回列表["()()","(())"]。
该题需要用递归去做,而且不是单一的f(n)=f(n-1)+str 这么简单的递归,要用到两层递归,才能遍历到所有可能的情况。具体见代码。

代码

Python
class Solution(object):
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        dic = {0:['']}         
        
        if n not in dic:
            dic[n] = []
            for i in xrange(n):
                for x in self.generateParenthesis(i):
                    for y in self.generateParenthesis(n-1-i):
                        #x有i个括号,已经有1个括号,y有n-1-i个括号
                        dic[n].append('('+x+')'+y)
            
        return dic[n]
Java
public class Solution {
    public List<String> generateParenthesis(int n) {
        HashMap<Integer,List<String>> map = new HashMap<Integer,List<String>>();
		
		List<String> list = new ArrayList<String>();
		
		list.add("");
		map.put(0, list);//map={0:[""]}
		List<String> nlist = new ArrayList<String>();
		
		if(!map.containsKey(n)) {
			map.put(n, nlist);//map={0:[""]...n:[]}
			
			for(int i = 0;i < n;i++) {
				List<String> jlist = this.generateParenthesis(i);
				for(int j = 0;j < jlist.size();j++) {
					List<String> klist = this.generateParenthesis(n-1-i);
					for(int k = 0;k < klist.size();k++)
					    //nlist里的字符串有n个括号,1+i+(n-1-i)=n
						nlist.add("("+jlist.get(j)+")"+klist.get(k));
				}
			}
		}
		
		return map.get(n);
    }
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值