📜  打印平衡括号的所有组合

📅  最后修改于: 2021-05-04 18:01:12             🧑  作者: Mango

编写一个函数以生成所有可能的n对平衡括号。

例子:

Input: n=1
Output: {}
Explantaion: This the only sequence of balanced 
parenthesis formed using 1 pair of balanced parenthesis. 

Input : n=2
Output: 
{}{}
{{}}
Explantaion: This the only two sequences of balanced 
parenthesis formed using 2 pair of balanced parenthesis. 
 

方法:用n对形成平衡括号子序列的所有序列。因此,有n个开括号和n个闭括号。
因此,子序列的长度为2 * n。有一个简单的想法,第i个字符可以是“{”当且仅当的“{”直到第i小于计数n和第i个字符可以是“}”当且仅当计数直到索引i为止,“ {”的值大于“}”的计数。如果遵循这两种情况,则最终的子序列将始终保持平衡。
因此,使用以上两种情况形成递归函数。

算法:

  1. 创建一个递归函数,它接受一个字符串(s),右括号(o)的计数和右括号(c)的计数以及n的值。
  2. 如果左括号和右括号的值等于n,则打印字符串并返回。
  3. 如果左括号的数量大于右括号的数量,则使用以下参数String s +“}” ,左括号的计数o ,右括号c +1和n递归调用该函数。
  4. 如果左方括号的数量小于n,则使用以下参数String s +“ {” ,左方括号o + 1 ,右方括号c和n递归调用该函数。

执行:

C++
// C++ program to print all
// combinations of balanced parentheses
#include 
#define MAX_SIZE 100
 
using namespace std;
 
void _printParenthesis(int pos, int n,
                       int open, int close)
{
    static char str[MAX_SIZE];   
      
    if (close == n)
    {
        cout << str << endl;
        return;
    }
    else
    {
        if (open > close)
        {
            str[pos] = '}';
            _printParenthesis(pos + 1, n, open,
                            close + 1);
        }
          
        if (open < n)
        {
            str[pos] = '{';
            _printParenthesis(pos + 1, n,
                             open + 1, close);
        }
    }
}
 
// Wrapper over _printParenthesis()
void printParenthesis(int n)
{
    if (n > 0)
        _printParenthesis(0, n, 0, 0);
         
    return;
}   
  
// Driver code
int main()
{
    int n = 3;
     
    printParenthesis(n);
 
    return 0;
}
 
// This code is contributed by hemanth lishetti


C
// C program to Print all combinations
// of balanced parentheses
# include
# define MAX_SIZE 100
 
void _printParenthesis(int pos, int n, int open, int close);
 
// Wrapper over _printParenthesis()
void printParenthesis(int n)
{
    if(n > 0)
        _printParenthesis(0, n, 0, 0);
    return;
}    
 
void _printParenthesis(int pos, int n, int open, int close)
{
    static char str[MAX_SIZE];    
     
    if(close == n)
    {
        printf("%s \n", str);
        return;
    }
    else
    {
        if(open > close)
        {
            str[pos] = '}';
            _printParenthesis(pos+1, n, open, close+1);
        }
         
        if(open < n)
        {
        str[pos] = '{';
        _printParenthesis(pos+1, n, open+1, close);
        }
    }
}
 
// Driver program to test above functions
int main()
{
    int n = 3;
    printParenthesis(n);
    getchar();
    return 0;
}


Java
// Java program to print all
// combinations of balanced parentheses
import java.io.*;
 
class GFG
{
    // Function that print all combinations of
    // balanced parentheses
    // open store the count of opening parenthesis
    // close store the count of closing parenthesis
    static void _printParenthesis(char str[], int pos, int n, int open, int close)
    {
        if(close == n)
        {
            // print the possible combinations
            for(int i=0;i close) {
                str[pos] = '}';
                _printParenthesis(str, pos+1, n, open, close+1);
            }
            if(open < n) {
                str[pos] = '{';
                _printParenthesis(str, pos+1, n, open+1, close);
            }
        }
    }
     
    // Wrapper over _printParenthesis()
    static void printParenthesis(char str[], int n)
    {
        if(n > 0)
        _printParenthesis(str, 0, n, 0, 0);
        return;
    }
     
    // driver program
    public static void main (String[] args)
    {
        int n = 3;
        char[] str = new char[2 * n];
        printParenthesis(str, n);
    }
}
 
// Contributed by Pramod Kumar


Python3
# Python3 program to
# Print all combinations
# of balanced parentheses
 
# Wrapper over _printParenthesis()
def printParenthesis(str, n):
    if(n > 0):
        _printParenthesis(str, 0,
                          n, 0, 0);
    return;
 
def _printParenthesis(str, pos, n,
                      open, close):
     
    if(close == n):
        for i in str:
            print(i, end = "");
        print();
        return;
    else:
        if(open > close):
            str[pos] = '}';
            _printParenthesis(str, pos + 1, n,
                              open, close + 1);
        if(open < n):
            str[pos] = '{';
            _printParenthesis(str, pos + 1, n,
                              open + 1, close);
 
# Driver Code
n = 3;
str = [""] * 2 * n;
printParenthesis(str, n);
 
# This Code is contributed
# by mits.


C#
// C# program to print all
// combinations of balanced parentheses
using System;
 
class GFG
{
    // Function that print all combinations of
    // balanced parentheses
    // open store the count of opening parenthesis
    // close store the count of closing parenthesis
    static void _printParenthesis(char []str,
            int pos, int n, int open, int close)
    {
        if (close == n)
        {
            // print the possible combinations
            for (int i = 0; i < str.Length; i++)
                Console.Write(str[i]);
             
            Console.WriteLine();
            return;
        }
        else
        {
            if (open > close) {
                str[pos] = '}';
                _printParenthesis(str, pos + 1,
                                n, open, close + 1);
            }
            if (open < n) {
                str[pos] = '{';
                _printParenthesis(str, pos + 1,
                                n, open + 1, close);
            }
        }
    }
     
    // Wrapper over _printParenthesis()
    static void printParenthesis(char []str, int n)
    {
        if(n > 0)
        _printParenthesis(str, 0, n, 0, 0);
        return;
    }
     
    // driver program
    public static void Main()
    {
        int n = 3;
        char[] str = new char[2 * n];
         
        printParenthesis(str, n);
    }
}
 
// This code is contributed by Sam007


PHP
 0)
        _printParenthesis($str, 0,
                          $n, 0, 0);
    return;
}
 
// Function that print
// all combinations of
    // balanced parentheses
    // open store the count of
    //  opening parenthesis
    // close store the count of
    //  closing parenthesis
function _printParenthesis($str, $pos, $n,
                           $open, $close)
{
    if($close == $n)
    {
        for ($i = 0;
             $i < strlen($str); $i++)
        echo $str[$i];
        echo "\n";
        return;
    }
    else
    {
        if($open > $close)
        {
            $str[$pos] = '}';
            _printParenthesis($str, $pos + 1, $n,
                              $open, $close + 1);
        }
         
        if($open < $n)
        {
        $str[$pos] = '{';
        _printParenthesis($str, $pos + 1, $n,
                          $open + 1, $close);
        }
    }
}
 
// Driver Code
$n = 3;
$str="     ";
printParenthesis($str, $n);
 
// This Code is contributed by mits.
?>


Javascript


输出:

{}{}{}
{}{{}}
{{}}{}
{{}{}}
{{{}}}

感谢Shekhu提供了以上代码。
复杂度分析:

  • 时间复杂度: O(2 ^ n)。
    对于每个索引,可以有两个选项'{‘或’}’。因此,可以说时间复杂度的上限为O(2 ^ n)或具有指数时间复杂度。
  • 空间复杂度: O(n)。
    如果使用全局变量或静态变量存储输出字符串,则可以将空间复杂度降低为O(n)。