您能告诉我如何在PROLOG中实现算法以生成N个平衡括号的所有组合吗? (方括号可正确关闭)
答案 0 :(得分:2)
这是dcg的最佳选择。我们为圆括号定义了一种语法,然后对其进行了枚举。
:- set_prolog_flag(double_quotes, chars).
balanced --> "".
balanced --> "(", balanced, ")", balanced.
现在,在询问具体句子时,最好使用library(double_quotes)
和this来查看更多信息。
我们可以要求固定长度的句子:
| ?- length(T, 6), phrase(balanced, T).
T = "()()()"
; T = "()(())"
; T = "(())()"
; T = "(()())"
; T = "((()))"
; false.
或者只增加一句话:
| ?- length(T, N), phrase(balanced, T).
T = [], N = 0
; T = "()", N = 2
; T = "()()", N = 4
; T = "(())", N = 4
; T = "()()()", N = 6
; T = "()(())", N = 6
; T = "(())()", N = 6
; T = "(()())", N = 6
; T = "((()))", N = 6
; T = "()()()()", N = 8
; T = "()()(())", N = 8
; T = "()(())()", N = 8
; T = "()(()())", N = 8
; T = "()((()))", N = 8
; ...
答案 1 :(得分:0)
这是获取加泰罗尼亚语数字的另一种解决方案。
它的括号类似于DCG解决方案:
catalan(L) :-
append(['('|A], [')'|B], L),
length(A, N), 0 =:= N mod 2,
catalan(A),
catalan(B).
catalan([]).
示例,验证A000108中的3个条目:
?- length(L, 18), findall(L, catalan(L), R),
length(R, N), write(N), nl, fail; true.
4862
?- length(L, 20), findall(L, catalan(L), R),
length(R, N), write(N), nl, fail; true.
16796
?- length(L, 22), findall(L, catalan(L), R),
length(R, N), write(N), nl, fail; true.
58786
答案 2 :(得分:0)
#include<iostream>
using namespace std;
void parenthesis(int open, int close, string brak)
{
if (open == 0 && close == 0)
cout<<brak;
if (open>close)
return;
if (open > 0)
parenthesis(open - 1, close,brak + "(");
if (close > 0)
parenthesis(open, close-1 ,brak + ")");
}
void printPar(int n)
{
parenthesis(n,n,"\n");
}
int main()
{
int n = 3;
printPar(n);
return 0;
}