使用 C 语言程序打印平衡括号表达式
给定四个变量 a、b、c、d,它们具有预定义的值,将根据使用的变量打印给定的括号。
其中变量:
a for (( b for () c for )( d for ))
任务是使用所有给定的括号并打印平衡括号表达式,如果我们无法形成平衡括号表达式,则打印 -1。如果有多个答案,我们可以打印可以使用给定括号形成的任何一个答案。
示例
Input: a = 3, b = 2, c = 4, d = 3 Output : (((((()()()()())))))()()
为了达到这个结果,我们可以首先检查是否可以使用给定的括号数量形成平衡括号表达式。如果可以使用给定的括号数量构成表达式,那么我们将:
- 打印 1 类括号的数量。
- 打印 3 类括号的数量。
- 打印 4 类括号的数量。
- 打印 2 类括号的数量。
以下是该方法的算法和实现。
算法
START Step 1 -> Declare Function void print(int a, int b, int c, int d) Declare int i IF ((a == d && a) || (a == 0 && c == 0 && d == 0)) Loop For i=1 and i<=a and i++ Print (( End Loop For i=1 and i<=c and i++ Print )( End Loop For i=1 and i<=d and i++ Print )) End Loop For i=1 and i<=b and i++ Print () End Else Print can’t be formed Step 2 -> main() Declare int a = 3, b = 2, c = 4, d = 3 Call print(a,b,c,d) STOP
示例
#include<stdio.h>
void print(int a, int b, int c, int d){
int i;
if ((a == d && a) || (a == 0 && c == 0 && d == 0)){
for (i = 1; i <= a; i++)
printf("((");
for (i = 1; i <= c; i++)
printf(")(");
for (i = 1; i <= d; i++)
printf("))");
for (i = 1; i <= b; i++)
printf("()");
}
else
printf("can't be formed");
}
int main(){
int a = 3, b = 2, c = 4, d = 3;
print(a, b, c, d);
return 0;
}输出
如果我们运行上述程序,它将生成以下输出
(((((()()()()())))))()()
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP