n个括号有多少种组合 (括号生成)---回溯法

一. 题目

描述
给出n对括号,请编写一个函数来生成所有的由n对括号组成的合法组合。
例如,给出n=3,解集为:
“((()))”, “(()())”, “(())()”, “()()()”, “()(())”,
示例1
输入:
1

返回值:
["()"]

示例2
输入:
2
复制
返回值:
["(())","()()"]

二. 思路

模拟加入左括号,右括号可以生成合法括号组合的过程直至所有左右括号都加入生成一个括号组合然后记录返回.

  1. 生成完整括号组合标志为加入的右括号个数r=n个括号数
  2. 可以合法加入左括号的条件为,左括号个数l < n个括号数
  3. 可以合法加入右括号的条件为, 左括号个数l> r右括号个数

三. 代码

import java.util.*;


public class Solution {
    /**
     * 
     * @param n int整型 
     * @return string字符串ArrayList
     */
    public ArrayList<String> generateParenthesis (int n) {
        // write code here
        ArrayList<Character> stack = new ArrayList();
        
        ArrayList<String> result = new ArrayList<>();
        
        int[] count = new int[1];
        
        fun(n, 0, 0, stack, result, count);
        
        return result;
        
        
    }
    
    public void fun (int n, int l, int r, ArrayList<Character> stack, ArrayList<String> result, int[] count) {
        if (stack.size() == 2 * n) {
            String temp = "";
            for (int i = 0; i < stack.size(); i++) {
                temp = temp + stack.get(i);
            }
            result.add(new String(temp));
            count[0] ++;
            return;
        }
        
        if (l < n ) {
            int size = stack.size();
            stack.add('(');
            l++;
            fun(n, l, r, stack, result, count); 
            stack.remove(size);
            l--;
            
            
            
        }
        
       if (l > r) {
            int size = stack.size();
            stack.add( ')');
            r++;
            fun(n, l, r, stack, result, count);
            stack.remove(size);
            r--;
        }
        
        
        
        
        
            
    }
    
    
}

四. 回溯法归纳总结(TODO)

  1. 回溯法
    https://baike.baidu.com/item/%E5%9B%9E%E6%BA%AF%E6%B3%95/86074

五. 参考资料

  1. n对括号的排列组合
    https://blog.csdn.net/dengyingjie123/article/details/83039580

  2. (递归)四对括号有多少种合法组合
    https://blog.csdn.net/qq_42396168/article/details/105844168

  3. 回溯算法最佳实践:括号生成
    https://labuladong.gitbook.io/algo/mu-lu-ye-3/mu-lu-ye/he-fa-kuo-hao-sheng-cheng

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值