Redian新闻
>
sum nested list 我连题目都没看懂T_T 求解答
avatar
sum nested list 我连题目都没看懂T_T 求解答# JobHunting - 待字闺中
l*4
1
题目是
Given a nested list of integers, returns the sum of all integers in the list
weighted by their depth. For example, given the list {{1,1},2,{1,1}} the
function should return 10 (four 1's at depth 2, one *2 at depth 1). Given
the list {1,{4,{6}}} the function should return 27 (one 1 at depth 1, one 4
at depth 2, and *one 6 at depth 3)
第二个例子我还能理解,第一个例子为啥有四个1在depth 2啊?难道不应该是两个1在
depth 1,一个2在depth 2,还有两个1在depth 3吗???
求拍醒
avatar
y*e
2
因为2在root level, 定于depth = 1, 把两个括号里的1看成它的children,depth = 2
avatar
l*4
3
。。好,那为啥要写成这样啊。。。{{1,1},2,{1,1}} 而不是 {2,{1,1,1,1,}}

2

【在 y*****e 的大作中提到】
: 因为2在root level, 定于depth = 1, 把两个括号里的1看成它的children,depth = 2
avatar
y*e
4
这个也是valid的写法啊这是含义不一样,两个大括号相当于左右两个子树,需要分别
traverse。
avatar
a*r
5
这个题目可以用stack来保存有几个{.然后每次用碰到的number * stack.size(). 如果
碰到}, st.pop()
基于这个解法。可以直接用一个cnt 来统计有几个{. 如果碰到{, cnt++. 如果}, cnt-
-. sum += cnt*num
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。