首页 > 其他 > 详细

《Cracking the Coding Interview》——第9章:递归和动态规划——题目6

时间:2014-03-20 21:21:13      阅读:485      评论:0      收藏:0      [点我收藏+]

2014-03-20 03:27

题目:输出所有由N对括号组成的合法的括号序列。比如n=2,“()()”、“(())”等等。

解法:动态规划配合DFS,应该也叫记忆化搜索吧。一个整数N总可以拆成若干个正整数的和,执行搜索的时候也是按照这个规则,将N序列拆成多个子序列进行搜索,同时将中间的搜索结果记录下来,以便下次再搜到的时候直接调用,省掉重复计算的开销。

代码:

bubuko.com,布布扣
 1 // 9.6 Print all valid parentheses sequences of n ()s.
 2 #include <iostream>
 3 #include <string>
 4 #include <vector>
 5 using namespace std;
 6 
 7 void DFS(int idx, int n, string s, vector<vector<string> > &result)
 8 {
 9     if (idx == n) {
10         result[n].push_back(s);
11         return;
12     } else {
13         int i, j;
14         for (i = 1; i <= n - idx; ++i) {
15             for (j = 0; j < (int)result[i - 1].size(); ++j) {
16                 DFS(idx + i, n, s + ( + result[i - 1][j] + ), result);
17             }
18         }
19     }
20 }
21 
22 int main()
23 {
24     vector<vector<string> > result;
25     int n;
26     int i;
27     
28     result.resize(1);
29     result[0].push_back("");
30     
31     while (cin >> n && n > 0) {
32         if (n >= (int)result.size()) {
33             for (i = (int)result.size(); i <= n; ++i) {
34                 result.push_back(vector<string>());
35                 DFS(0, i, "", result);
36             }
37         }
38         for (i = 0; i < (int)result[n].size(); ++i) {
39             cout << result[n][i] << endl;
40         }
41     }
42     
43     return 0;
44 }
bubuko.com,布布扣

《Cracking the Coding Interview》——第9章:递归和动态规划——题目6,布布扣,bubuko.com

《Cracking the Coding Interview》——第9章:递归和动态规划——题目6

原文:http://www.cnblogs.com/zhuli19901106/p/3612795.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!