You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python数学游戏算法开发:列表路径求和问题问询

路径累加问题解决方案

Hey,我来帮你搞定这个位置移动累加的问题!先把核心规则再明确一遍,避免理解偏差:

  • 给定列表首元素固定为0(起始位置),其余为随机正整数,长度在5-10之间
  • 从索引0开始,每次只能选择向右移动1位或者跳过1位移动到下下个位置
  • 每到达一个新位置,就把该位置的数值累加到总和里

下面我会给出两种常见的实现思路和代码示例,按需选择即可:

1. 遍历所有可能路径(递归法)

如果需要查看所有可行路径及其对应的总和,递归回溯的方式最直观,能清晰展示每一种移动选择的结果:

def calculate_all_paths(positions):
    # 存储所有路径的索引序列和对应总和
    path_results = []
    
    def backtrack(current_idx, current_total, path):
        # 到达列表末尾,记录当前路径和总和
        if current_idx >= len(positions):
            path_results.append((path.copy(), current_total))
            return
        
        # 累加当前位置的数值,并记录索引
        updated_total = current_total + positions[current_idx]
        path.append(current_idx)
        
        # 选择1:移动到下一个位置(current_idx + 1)
        if current_idx + 1 < len(positions):
            backtrack(current_idx + 1, updated_total, path)
        # 选择2:移动到下下个位置(current_idx + 2)
        if current_idx + 2 < len(positions):
            backtrack(current_idx + 2, updated_total, path)
        
        # 回溯,移除当前索引,尝试其他路径
        path.pop()
    
    # 从起始位置(索引0)开始遍历
    backtrack(0, 0, [])
    return path_results

# 测试示例
test_positions = [0, 10, 50, 45, 80, 5, 35]
all_paths = calculate_all_paths(test_positions)

print("所有可行路径及对应总和:")
for idx_path, total in all_paths:
    value_path = [test_positions[idx] for idx in idx_path]
    print(f"索引路径:{idx_path} | 数值序列:{value_path} | 累加总和:{total}")

运行这段代码后,你会得到所有可能的移动路径,以及每条路径最终的累加总和,非常适合调试和验证逻辑。

2. 求最大/最小累加总和(动态规划法)

如果你的目标是找到总和最大或者总和最小的路径,动态规划会是更高效的方案(时间复杂度仅为O(n)):

求最大总和的实现

def get_max_total(positions):
    n = len(positions)
    if n == 0:
        return 0
    if n == 1:
        return positions[0]
    
    # dp[i] 表示到达第i个位置时的最大累加总和
    dp = [0] * n
    dp[0] = positions[0]  # 起始位置只能是0
    dp[1] = dp[0] + positions[1]  # 从0只能移动1位到1
    
    for i in range(2, n):
        # 到达i位置的最优解 = 前两个位置的最优解中较大的那个 + 当前位置数值
        dp[i] = max(dp[i-1], dp[i-2]) + positions[i]
    
    return dp[-1]

# 测试示例
test_positions = [0, 10, 50, 45, 80, 5, 35]
print(f"最大累加总和:{get_max_total(test_positions)}")

求最小总和的实现

只需要把上面代码中的max换成min即可:

def get_min_total(positions):
    n = len(positions)
    if n == 0:
        return 0
    if n == 1:
        return positions[0]
    
    dp = [0] * n
    dp[0] = positions[0]
    dp[1] = dp[0] + positions[1]
    
    for i in range(2, n):
        dp[i] = min(dp[i-1], dp[i-2]) + positions[i]
    
    return dp[-1]

关键逻辑说明

  • 递归法通过回溯遍历所有可能的移动选择,适合需要完整路径信息的场景,但对于较长列表(比如10个元素),路径数量会指数级增长
  • 动态规划法通过记录每个位置的最优解,避免重复计算,适合只需要最优结果的场景,效率更高

内容的提问来源于stack exchange,提问作者Ben Roux

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:07:12