【字节青训】:数字分组求偶数和

75 阅读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

题目链接:数字分组求偶数和 - MarsCode

思路

  • 先把数字数组转化为字符串数组进行存取,然后进行 dfs 深度搜索遍历即可,注意递归条件
#include <iostream>
#include <vector>
#include <string>

int n, ans;
void dfs(std::vector<std::string> s, int u, int sum)
{
    if (u == n && sum % 2 == 0) {
        ans++;
        return;
    }

    for (int i = 0; i < s[u].size(); i++)
    {
        char ch = s[u][i];
        dfs(s, u + 1, sum + (ch - '0'));
    }

}

int solution(std::vector<int> numbers) {
    // Please write your code here
    n = numbers.size();
    ans = 0;
    std::vector<std::string> s(n + 1);
    for (int i = 0; i < n; i++)
    {
        s[i] = std::to_string(numbers[i]);
    }
    dfs(s, 0, 0);
    //cout << ans << endl;
    return ans;
}

int main() {
    // You can add more test cases here
    std::cout << (solution({123, 456, 789}) == 14) << std::endl;
    std::cout << (solution({123456789}) == 4) << std::endl;
    std::cout << (solution({14329, 7568}) == 10) << std::endl;
    return 0;
}