Nested List Weight Sum II

本文介绍了一种针对嵌套整数列表求和的算法,该算法首先计算列表的最大深度,然后根据深度对列表中的每个元素进行加权求和。通过递归方式处理嵌套结构,实现了逆序加权求和的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习了一种,先算最大的深度,再计算的思路。

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * public interface NestedInteger {
 *
 *     // @return true if this NestedInteger holds a single integer, rather than a nested list.
 *     public boolean isInteger();
 *
 *     // @return the single integer that this NestedInteger holds, if it holds a single integer
 *     // Return null if this NestedInteger holds a nested list
 *     public Integer getInteger();
 *
 *     // @return the nested list that this NestedInteger holds, if it holds a nested list
 *     // Return null if this NestedInteger holds a single integer
 *     public List<NestedInteger> getList();
 * }
 */
public class Solution {
    public int depthSumInverse(List<NestedInteger> nestedList) {
        int maxDepth = 1;
        if (nestedList == null || nestedList.size() == 0) {
            return 0;
        }
        maxDepth = maxDepth(nestedList, maxDepth);
        int res = sum(nestedList, maxDepth);
        return res;
    }
    
    private int sum(List<NestedInteger> nestedList, int depth) {
        int sum = 0;
        for (NestedInteger nestedInteger: nestedList) {
            if (nestedInteger.isInteger()) {
                sum = sum + nestedInteger.getInteger() * depth;
            } else {
                sum = sum + sum(nestedInteger.getList(), depth - 1);
            }
        }
        return sum;
    }
    
    private int maxDepth(List<NestedInteger> nestedList, int depth) {
        int max = depth;
        for (NestedInteger nestedInteger: nestedList) {
            if (!nestedInteger.isInteger()) {
                max = Math.max(max, maxDepth(nestedInteger.getList(), depth + 1));
            }
        }
        return max;
    }
}


<think>我们被要求计算Python列表中所有元素的总和。根据引用[1][2][3]的内容,有几种方法可以实现: 1. 使用循环(for或while) 2. 使用递归 3. 使用内置函数sum() 其中,引用[2]特别提到使用内置函数sum()是最简单直接的方式。 因此,我们可以推荐以下方法: 方法1(推荐):使用内置函数sum() 方法2:使用for循环 方法3:使用while循环 方法4:使用递归(注意:递归有深度限制,不适用于长列表) 下面分别给出示例代码:</think>在 Python 中计算列表元素总和有多种高效方法,以下是详细解决方案: ### 方法一:使用内置函数 `sum()`(推荐) ```python my_list = [12, 15, 3, 10] total = sum(my_list) print("列表元素总和为:", total) # 输出: 40 ``` - **优点**:简洁高效,时间复杂度 $O(n)$[^2] - **适用场景**:所有数值型列表(整数、浮点数) ### 方法二:使用 `for` 循环 ```python my_list = [12, 15, 3, 10] total = 0 for num in my_list: total += num print("列表元素总和为:", total) # 输出: 40 ``` - **优点**:逻辑清晰,可添加额外处理逻辑 - **变体**(使用索引): ```python total = 0 for i in range(len(my_list)): total += my_list[i] ``` ### 方法三:使用 `while` 循环 ```python my_list = [12, 15, 3, 10] total = 0 index = 0 while index < len(my_list): total += my_list[index] index += 1 print("列表元素总和为:", total) # 输出: 40 ``` ### 方法四:使用递归(仅限学习,不推荐实战) ```python def list_sum(lst, n): if n == 0: return 0 return lst[n-1] + list_sum(lst, n-1) my_list = [12, 15, 3, 10] total = list_sum(my_list, len(my_list)) print("列表元素总和为:", total) # 输出: 40 ``` ⚠️ **注意**:Python 默认递归深度约 1000 层,长列表会触发 `RecursionError` ### 特殊类型处理 1. **混合类型列表**(需先过滤): ```python mixed_list = [1, 2.5, "3", 4] numbers = [x for x in mixed_list if isinstance(x, (int, float))] print(sum(numbers)) # 输出: 7.5 ``` 2. **嵌套列表求和**(使用递归): ```python def nested_sum(lst): total = 0 for item in lst: if isinstance(item, list): total += nested_sum(item) else: total += item return total nested_list = [1, [2, [3, 4], 5]] print(nested_sum(nested_list)) # 输出: 15 ``` ### 性能对比 | 方法 | 时间复杂度 | 适用场景 | |------------|------------|--------------------------| | `sum()` | $O(n)$ | 通用场景(推荐) | | `for`循环 | $O(n)$ | 需逐元素处理时 | | 递归 | $O(n)$ | 学习用途(实际避免使用) | > **最佳实践**:优先使用内置函数 `sum()`,它针对列表求和进行了底层优化,比手动循环快 2-5 倍[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值