【问题标题】:Recursion - Score Of Parentheses递归 - 括号分数
【发布时间】:2023-04-09 11:40:02
【问题描述】:

我正在尝试使用递归解决括号分数的leet代码问题。

https://leetcode.com/problems/score-of-parentheses/

我想明确地使用递归。对于这样的情况它失败了 (())() 预期答案是 3,我返回 4。如何使用递归解决这个问题?

    public int scoreOfParentheses(String S) {
        return paran(S, 0);
    }

    int paran(String s, int c){
        // base case exit
        if(c >= s.length())
            return 0;
        if(s.charAt(c) == '(' && s.charAt(c + 1) == ')'){
            return 1 + paran(s, c + 2);
        }
        else if(s.charAt(c) == '('){
            return 2 * paran(s, c + 1);
        }
        return paran(s , c + 1);
    }

【问题讨论】:

    标签: java algorithm recursion


    【解决方案1】:

    我会这样做,使用 int[] 来跟踪字符串的进度。

    static int score(String str, int[] i) {
        int score=0;
        while (i[0]<str.length()) {
            char c=str.charAt(i[0]++);
            if (c=='(') {
                int val=score(str,i);
                if (val==0) {
                    score++;
                } else {
                    score+=2*val;
                }
            } else {
                return score;
            }
        }
        return score;
    }
    

    【讨论】:

      【解决方案2】:

      这是一个被法官接受的没有循环或全局引用的递归。它不仅返回分数,还返回一个元组[score, index_after_parenthetical]

      JavaScript 代码:

      function f(s, i=0){
        if (i == s.length)
          return [0, i];
          
        if (s[i] == '('){
          const [inner, j] = f(s, i + 1);  
          const [after, k] = f(s, j);
      
          return [2 * (inner || 0.5) + after, k];
        }
      
        return [0, i + 1];
      }
      
      var strs = ["(())", "(()(()))"];
      
      for (const s of strs)
        console.log(s + ': ' + f(s));

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-18
        • 1970-01-01
        • 1970-01-01
        • 2022-12-04
        • 2012-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多