数字分组求偶数和 | 豆包MarsCode AI 刷题

71 阅读3分钟

问题描述

小M面对一组从 1 到 9 的数字,这些数字被分成多个小组,并从每个小组中选择一个数字组成一个新的数。目标是使得这个新数的各位数字之和为偶数。任务是计算出有多少种不同的分组和选择方法可以达到这一目标。

  • numbers: 一个由多个整数字符串组成的列表,每个字符串可以视为一个数字组。小M需要从每个数字组中选择一个数字。

例如对于[123, 456, 789],14个符合条件的数为:147 149 158 167 169 248 257 259 268 347 349 358 367 369


测试样例

样例1:

输入:numbers = [123, 456, 789]
输出:14

样例2:

输入:numbers = [123456789]
输出:4

样例3:

输入:numbers = [14329, 7568]
输出:10

def solution(numbers): # 用来存储组合数量的计数器 total_count = 0

# 用于生成所有组合的辅助函数
def generate_combinations(index, current_sum):
    nonlocal total_count
    # 如果已选择所有组,检查当前和是否为偶数
    if index == len(numbers):
        if current_sum % 2 == 0:
            total_count += 1
        return
    
    # 遍历当前组中的每个数字(转换为字符串以便按字符处理)
    for num in str(numbers[index]):
        generate_combinations(index + 1, current_sum + int(num))

# 从第一个组开始生成组合
generate_combinations(0, 0)

return total_count

测试样例

if name == "main": print(solution([123, 456, 789]) == 14) print(solution([123456789]) == 4) print(solution([14329, 7568]) == 10)

在这段代码中:

  1. solution函数

    • 这是整个问题的主要解决函数,它接受一个列表numbers作为参数,列表中的每个元素也是一个数字字符串,表示一个数字组。
    • 函数内部定义了一个变量total_count,用于记录满足各位数字之和为偶数的组合数量,初始值为 0。
    • 然后定义了一个内部函数generate_combinations来递归地生成所有可能的数字组合。
  2. generate_combinations函数

    • 这个函数接受两个参数:index表示当前正在处理的数字组的索引,current_sum表示到目前为止已经选择的数字之和。

    • index等于numbers列表的长度时,意味着已经从每个数字组中都选择了一个数字,此时检查current_sum是否为偶数,如果是,则将total_count加 1。

    • 否则,对于当前数字组(通过numbers[index]访问)中的每个数字,先将其转换为整数并加到current_sum上,然后递归调用generate_combinations函数来处理下一个数字组(index + 1)。

最后,通过以下测试样例来验证函数的正确性: if name == "main": print(solution([123, 456, 789]) == 14) print(solution([123456789]) == 4) print(solution([14329, 7568]) == 10)