📜  使用树的括号分数

📅  最后修改于: 2021-06-26 10:13:29             🧑  作者: Mango

给定一个字符串str ,其中包含成对的圆括号,任务是根据给定的规则计算给定字符串的分数:

  1. “()”的得分为1。
  2. “ x y”的得分为x + y,其中x和y是一对独立的括号对。
  3. “(x)”的分数是x的两倍,即分数是2 * x的分数。

例子:

方法:想法是使用树数据结构与递归一起解决此问题。

  • 我们树形结构的根节点将代表我们输入括号的最外面的一对。
  • 对于最外面的括号内包含的每对平衡括号,我们将向其根节点添加一个子对象。
  • 将孩子声明为根节点的过程将是递归的,因此它将为层次结构中的每对平衡括号在树结构中创建一个节点。
  • 每个平衡的括号对都将被视为最外面的(递归)并生成一个节点,因此将使我们能够计算分数。
  • 在计算分数时,我们树的每个叶节点的分数都将被视为1,并且要获取其相应根节点的分数,我们需要将每个子节点的分数相加,并将其加倍。
  • 下图显示了生成的树的递归结构,我们从底部开始计算每个级别的分数,直到到达最外面的括号为止。

下面是上述方法的实现:

C++
// C++ program to find the score of
// parentheses using Tree
 
#include 
#include 
 
using namespace std;
 
// Customized tree class or struct,
// contains all required methods.
class TreeNode {
    TreeNode* parent = NULL;
    vector children;
 
public:
    // Function to add a child into
    // the list of children
    void addChild(TreeNode* node)
    {
        children.push_back(node);
    }
 
    // Function to change the parent
    // pointer to the node passed
    void setParent(TreeNode* node)
    {
        parent = node;
    }
 
    // Function to return the parent
    // of the current node
    TreeNode* getParent()
    {
        return parent;
    }
 
    // Function to compute the score recursively.
    int computeScore()
    {
 
        // Base case
        if (children.size() == 0)
            return 1;
 
        int res = 0;
 
        // Adds scores of all children
        for (TreeNode* curr : children)
            res += curr->computeScore();
 
        if (parent == NULL)
            return res;
        else
            return 2 * res;
    }
};
 
// Function to create the tree structure
TreeNode* computeTree(string s)
{
 
    TreeNode* current = new TreeNode();
    TreeNode* root = current;
 
    // Creating a node for every "()"
    for (int i = 0; i < s.size(); i++) {
 
        // If we find "(" we add a node as
        // a child
        if (s[i] == '(') {
            TreeNode* child = new TreeNode();
            child->setParent(current);
            current->addChild(child);
            current = child;
        }
 
        // On finding ")" which confirms that
        // a pair is closed, we go back
        // to the parent
        else {
 
            current = current->getParent();
        }
    }
    return root;
}
 
// Driver code
int main()
{
    string s = "(()(()))";
 
    // Generating the tree
    TreeNode* root = computeTree(s);
 
    // Computing the score
    cout << root->computeScore();
    return 0;
}


Python3
# Python3 program to find the score of
# parentheses using Tree
  
# Customized tree class or struct,
# contains all required methods.
class TreeNode:
     
    def __init__(self):
        self.parent = None
        self.children = []
 
    # Function to add a child into
    # the list of children
    def addChild(self, node):
         
        self.children.append(node);
     
    # Function to change the parent
    # pointer to the node passed
    def setParent(self, node):
     
        self.parent = node;
  
    # Function to return the parent
    # of the current node
    def getParent(self):
     
        return self.parent;
  
    # Function to compute the score recursively.
    def computeScore(self):
         
        # Base case
        if (len(self.children) == 0):
            return 1;
  
        res = 0;
  
        # Adds scores of all children
        for curr in self.children:
         
            res += curr.computeScore();
  
        if (self.parent == None):
            return res;
        else:
            return 2 * res;
     
# Function to create the tree structure
def computeTree(s):
  
    current = TreeNode();
    root = current;
  
    # Creating a node for every "()"
    for i in range(len(s)):
  
        # If we find "(" we add a node as
        # a child
        if (s[i] == '('):
             
            child = TreeNode();
            child.setParent(current);
            current.addChild(child);
            current = child;
  
        # On finding ")" which confirms that
        # a pair is closed, we go back
        # to the parent
        else:
  
            current = current.getParent();
             
    return root;
 
# Driver code
if __name__=='__main__':
     
    s = "(()(()))";
  
    # Generating the tree
    root = computeTree(s);
  
    # Computing the score
    print(root.computeScore())
     
    # This code is contributed by rutvik_56


C#
// C# program to find the score of
// parentheses using Tree
using System;
using System.Collections;
 
class GFG{
     
// Customized tree class or struct,
// contains all required methods.
class TreeNode
{
    public TreeNode parent = null;
    public ArrayList children = new ArrayList();
     
    // Function to add a child into
    // the list of children
    public void addChild(TreeNode node)
    {
        children.Add(node);
    }
     
    // Function to change the parent
    // pointer to the node passed
    public void setParent(TreeNode node)
    {
        parent = node;
    }
     
    // Function to return the parent
    // of the current node
    public TreeNode getParent()
    {
        return parent;
    }
     
    // Function to compute the score
    // recursively.
    public int computeScore()
    {
         
        // Base case
        if (children.Count == 0)
            return 1;
             
        int res = 0;
         
        // Adds scores of all children
        foreach(TreeNode curr in children)
            res += curr.computeScore();
  
        if (parent == null)
            return res;
        else
            return 2 * res;
    }
};
  
// Function to create the tree structure
static TreeNode computeTree(string s)
{
    TreeNode current = new TreeNode();
    TreeNode root = current;
     
    // Creating a node for every "()"
    for(int i = 0; i < s.Length; i++)
    {
         
        // If we find "(" we add a node as
        // a child
        if (s[i] == '(')
        {
            TreeNode child = new TreeNode();
            child.setParent(current);
            current.addChild(child);
            current = child;
        }
  
        // On finding ")" which confirms that
        // a pair is closed, we go back
        // to the parent
        else
        {
            current = current.getParent();
        }
    }
    return root;
}
  
// Driver code
public static void Main()
{
    string s = "(()(()))";
     
    // Generating the tree
    TreeNode root = computeTree(s);
  
    // Computing the score
    Console.Write(root.computeScore());
}
}
 
// This code is contributed by pratham76


输出:
6

时间复杂度: O(N) ,其中N是输入字符串的长度。
空间复杂度: O(N) ,其中N是输入字符串的长度。

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。