• 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 };
  • 相关阅读:
    飘逸的python
    hdu 4512 吉哥系列故事——完美队形I(最长公共上升自序加强版)
    Codeforces 482B. Interesting Array 线段树
    《开源框架那些事儿21》:巧借力与借巧力
    openNebula libvirt-virsh attach disk device for kvm
    configure mount nfs
    opennebula kvm attach disk
    openNebula 运维系列虚拟机virtual machines operations
    yum subversion puppet puppet-server
    文件系统,快存储,对象存储
  • 原文地址:https://www.cnblogs.com/CheeseZH/p/5012102.html
Copyright © 2020-2023  润新知