def sum_nested_array(arr):
total = 0
for item in arr:
if isinstance(item, list):
total += sum_nested_array(item)
else:
total += item
return total
# 性能优化思路:
1. **减少不必要的递归调用**:可以通过使用栈(stack)来模拟递归过程,从而避免系统递归调用的开销。例如:
```python
def sum_nested_array_with_stack(arr):
total = 0
stack = arr.copy()
while stack:
item = stack.pop()
if isinstance(item, list):
stack.extend(item)
else:
total += item
return total
- 减少迭代次数:在迭代过程中,提前判断数组长度,如果长度为0,可以直接返回0,避免不必要的迭代。例如:
def sum_nested_array_optimized(arr):
if not arr:
return 0
total = 0
for item in arr:
if isinstance(item, list):
total += sum_nested_array_optimized(item)
else:
total += item
return total