04 数字分组求偶数和

215 阅读2分钟

数字分组求偶数和

题目描述

小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

💡Idea

  • 一个数的数位和是否是偶数 sum % 2 == 0

  • For instance, 987这个数字,选择9,如果数位和原来为偶数,则现在奇数,原来为奇数,现在为偶数,选择8,数位和原来为偶数,现在为0数,数位和原来为奇数,现在为奇数

    • dp = [1, 0]dp[0]代表位数和为偶数的个数,dp[1]代表位数和为奇数的个数
  • 对于每个数字,得出其偶数、奇数贡献值,累加到最后的数字,模拟挑选数字

  • 设置现在数字状态thisPartDp和前数字组合状态preDp

    • {thisPartDp[0]+=preDp[0]thisPartDp[1]+=PreDp[1] if x=偶数thisPartDp[0]+=preDp[1]thisPartDp[1]+=preDp[0] if x=奇数\begin{cases} thisPartDp[0] += preDp[0] \\ thisPartDp[1] += PreDp[1] & \text{ if } x=偶数\\ thisPartDp[0] += preDp[1] \\ thisPartDp[1] += preDp[0] & \text{ if } x=奇数 \end{cases}

代码如下:

def solution(numbers):
    # Please write your code here
    preDp = [1, 0]
    for subs in numbers:
        thisPartDp = [0, 0]
        while subs:
            c = subs % 10
            subs //= 10
            c_mod = c % 2 # 0 or 1
            thisPartDp[0] += preDp[c_mod]
            thisPartDp[1] += preDp[(c_mod + 1) % 2]
        preDp = thisPartDp # 状态转移
        print(preDp)
    return preDp[0]

Ending ...