LeetCode题解——22. 括号生成(递归?)

题目

https://leetcode-cn.com/problems/generate-parentheses/
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

例如,给出 n = 3,生成结果为:

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

思路

(1)一开始想的是生成1个的,然后生成2个的,()插进去一个的,以此递推,想了下重复性判断有点困难,放弃。
(2)想了下DP,感觉不像DP类题目。
(3)想了下规律,加入n为2
(-> 可左可右
((->可右可右
()->可左可右
...
干脆直接递归调用,试一下,测试代码打了个100超时,手抖点了提交竟然通过了。

i为左括号可用数量,right为右括号可用数量
			f(i-1,j),i>0
f(i,j) = 
			f(i,j-1),j>0且i<j

代码

import java.util.ArrayList;
import java.util.List;

public class Solution_22 {
    public static void main(String[] args) {
        generateParenthesis(5);
    }

    public static List<String> generateParenthesis(int n) {
        List<String> list = new ArrayList<>();
        core(list, "", n, n);
        return list;
    }

    public static void core(List<String> list, String current, int left, int right) {
    	// 递归出口
        if (left == 0 && right == 0) {
            list.add(current);
            return;
        }
        // 优先左,第一个必须是"("
        if (left > 0) {
            core(list, current + "(", left - 1, right);
        }
        // 要合法,left必须小于right
        if (right > 0 && left < right) {
            core(list, current + ")", left, right - 1);
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值