Leetcode: Generate parentheses

输入n,输出n个左括号和n个右括号的合法括号序列

关键:当前位置的左括号不少于右括号

图:

  节点:当前位置左括号和右括号的个数(x, y)(x>=y)

  边:从(x, y)到(x+1, y)或(x,y+1)

  x==y时,只有(x+1,y)这条边

解:从(0,0)出发到(n,n)的全部路径

====================

C++

DFS

记录什么

  左右括号的个数

  当前的部分解

 1 class Solution {
 2 public:
 3     void helperDFS(int n, int x, int y, string now, vector<string> &ans) {
 4         if (y == n) {
 5             ans.push_back(now);
 6             return;
 7         }
 8         if (x < n) {
 9             helperDFS(n, x + 1, y, now + "(", ans);
10         }
11         if (x > y) {
12             helperDFS(n, x, y + 1, now + ")", ans);
13         }
14         
15     }
16     vector<string> generateParenthesis(int n) {
17         vector<string> ans;
18         helperDFS(n, 0, 0, "", ans);
19         return ans;
20     }
21 };

C++

BFS

  记录什么

  方法1:当前的部分解

  方法2:每个节点记录能到达它之前的节点集合(麻烦,最后还要还原路径)

 1 struct node{
 2     int x, y;
 3     string now;
 4 };
 5 class Solution {
 6 public:
 7     void helperBFS(int n, vector<string> &ans) {
 8         if (0 == n) {
 9             ans.push_back("");
10             return;
11         }
12         node tmp;
13         tmp.x = tmp.y = 0;
14         tmp.now = "";
15         queue<node> q;
16         for (q.push(tmp); !q.empty(); q.pop()) {
17             tmp = q.front();
18             node other;
19             if (tmp.x < n) {
20                 other.x = tmp.x + 1;
21                 other.y = tmp.y;
22                 other.now = tmp.now + "(";
23                 q.push(other);
24             }
25             if (tmp.x > tmp.y) {
26                 other.x = tmp.x;
27                 other.y = tmp.y + 1;
28                 other.now = tmp.now + ")";
29                 if (other.y == n) {
30                     ans.push_back(other.now);
31                 } else {
32                     q.push(other);
33                 }
34             }
35         }
36         
37     }
38     vector<string> generateParenthesis(int n) {
39         vector<string> ans;
40         helperBFS(n, ans);
41         return ans;
42     }
43 };

 

posted @ 2015-12-02 10:06  ZH奶酪  阅读(320)  评论(0编辑  收藏  举报