力扣 856. 括号的分数 递归/栈/数学
发布日期:2021-11-05 06:59:30 浏览次数:14 分类:技术文章

本文共 921 字,大约阅读时间需要 3 分钟。

在这里插入图片描述
思路一: d f s dfs dfs,考虑当前位置 i d x idx idx ( ( (,那么下一位置要么为 ) ) )要么为 ( ( (,如果是前者,那么当前层的分数加1,如果是后者,就需要进入更深一层计算。

class Solution {
public: int scoreOfParentheses(string S) {
int idx=0; return dfs(S,idx); } int dfs(string &s,int &idx){
int siz=s.size(),val=0; while(idx

思路二:思路一可以用栈来实现。

class Solution {
public: int scoreOfParentheses(string S) {
stack
s; s.push(0); for(auto ch:S){
if(ch=='(') s.push(0); else{
int v1=s.top(); s.pop(); int v2=s.top(); s.pop(); s.push(v2+max(v1<<1,1)); } } return s.top(); }};

思路三:数学。显然只有最里面的 ( ) () ()才能实际贡献分数,而这个分数和其所位于的深度有关系。

class Solution {
public: int scoreOfParentheses(string S) {
int deep=0,ans=0,siz=S.size(); for(int i=0;i

转载地址:https://blog.csdn.net/xiji333/article/details/107968405 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:力扣 面试题 03.02. 栈的最小值 双栈
下一篇:力扣 1130. 叶值的最小代价生成树 区间dp/单调栈

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月17日 23时31分09秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章