打印括号的合法组合
2012-07-31 10:50
225 查看
From career up 150.
Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n-pairs of parentheses.
运行结果:
Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n-pairs of parentheses.
#include <iostream> using namespace std; const int n = 3; char a[n * 2]; void print(int l, int r, int i) { if(l < 0 || r < l){ return; } if (l==0 && r==0) { for (int j = 0; j < n * 2; j++) { cout << a[j] << " "; } cout << endl; } else { if (l > 0) { a[i] = '('; print(l - 1, r, i + 1); } if (r > l) { a[i] = ')'; print(l, r - 1, i + 1); } } } int main() { print(3, 3, 0); }
运行结果:
( ( ( ) ) ) ( ( ) ( ) ) ( ( ) ) ( ) ( ) ( ( ) ) ( ) ( ) ( )
相关文章推荐
- 打印包含n个括号的所有合法的组合
- 打印n对括号匹配的所有组合
- 打印所有匹配括号组合
- 打印n对括号的全部有效组合
- 打印N对括号的全部有效组合
- 判断括号字符串是否为合法+求n对括号的所有组合
- 打印n对括号的全部有效组合(即左右括号正确配对)
- 打印n对括号的全部有效组合(即左右括号正确配对)
- 20. Valid Parentheses--合法的括号组合(使用stack)
- 求n对括号的合法组合
- 打印所有合法的括号序列
- 打印出所有可能的括号组合
- N对括号的合法组合
- 【算法】打印N对合理括号组合
- 9.9递归和动态规划(六)——打印n对括号的全部有效组合(即左右括号正确配对)
- 【卡特兰数】有N对括号,输出所有合法的组合
- 输出所有的合法的括号组合
- 9.9递归和动态规划(六)——打印n对括号的所有有效组合(即左右括号正确配对)
- 面试编程题拾遗(06) --- 打印n对括号的全部有效组合
- 程序员面试金典: 9.9 递归和动态规划 9.6打印n对括号的全部有效组合