LeetCode0022——括号生成——DFS

这道题是一道基于深度优先搜索的字符串类问题,题目描述如下:
在这里插入图片描述
这道题也就是要挨个找出所有有效的的成对的括号,有效的可以总结如下:
1)开头的第一个元素必是左括号
2)只有前面还有未配对的左括号,才可以有右括号出现
3)使用的括号对数恰好为n

所以这题的深度优先搜索是有条件约束的,给出我写的代码:

	/*
    Result is the vector storing the result string
    LeftCounter is the number of Left bracket can be used
    RightCounter is the number of right bracket can be used
    n is the number of pairs
    */
    void DFS(vector<string>& Result, string PresentString, int LeftCounter, int RightCounter, int n)
    {
    
    
        // the terminal of DFS
        if(PresentString.size() == n * 2)
        {
    
    
            Result.push_back(PresentString);
            return;
        }

        // if there are remained left bracket
        if(LeftCounter)
            DFS(Result, PresentString + '(', LeftCounter - 1, RightCounter + 1, n);
        
        if(RightCounter)
            DFS(Result, PresentString + ')', LeftCounter, RightCounter - 1, n);
    }

public:
    vector<string> generateParenthesis(int n) {
    
    
        vector<string> Result;
        DFS(Result, "(", n - 1, 1, n);
        return Result;
    }

我使用了两个变量LeftCounter和RightCounter来记录还可以使用的左右括号的个数,左括号的可使用个数受制于括号的总对数,右括号的可使用个数受制于其之前出现的但并未配对的左括号个数。当LeftCounter不为0时,表示当前还有可用的左括号(加入字符串),同时因为使用了一个左括号,那么LeftCounter的值应该-1,而可用的右括号的值RightCounter应该+1,写成代码如下所示:

 // if there are remained left bracket
 if(LeftCounter)
 	DFS(Result, PresentString + '(', LeftCounter - 1, RightCounter + 1, n);

同理,使用一个右括号时,可用的左括号不变,右括号值-1,代码如下:

 if(RightCounter)
  	DFS(Result, PresentString + ')', LeftCounter, RightCounter - 1, n);

最终在main函数中只需要调用DFS递归的进行求解即可,考虑到第一个符号必为左括号,那么初始调用时传入的参数为:

DFS(Result, "(", n - 1, 1, n);

这就是我对这道题的全部思路。

Guess you like

Origin blog.csdn.net/zzy980511/article/details/115490601