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

C++如何生成二维字符数组长度1至最大行的所有元素组合

实现思路
  • 先预处理二维数组,逐行提取有效字符存储,同时统计存在有效字符的总行数(即组合的最大长度),有效字符的判断规则可根据实际空白定义调整。
  • 长度为k的组合本质是前k行有效字符的笛卡尔积,采用迭代方式逐行拼接生成所有组合,逻辑简单易实现。
  • 按要求的格式分长度输出所有生成的单词。
C++ 实现代码
#include <iostream>
#include <vector>
#include <string>
using namespace std;

// 自定义有效字符判断规则,可根据实际空白定义修改
bool is_valid(unsigned char c) {
    // 示例中空白为空格,若空白是'\0'可删除空格判断
    return c != ' ' && c != '\0';
}

int main() {
    // 可根据实际数组大小修改行列常量
    const int rows = 10, columns = 10;
    // 示例二维数组初始化,空白位置填充空格
    unsigned char arr[rows][columns] = {
        {'l','m','n',' ',' ',' ',' ',' ',' ',' '},
        {'v','g','h','k','l','Z','a','b','d',' '},
        {'M','q','r','u','v','g','h','k','l',' '},
        {'M','Q','R','Z','a','b','d',' ',' ',' '},
        {'M','Q','R','d',' ',' ',' ',' ',' ',' '},
        {'d',' ',' ',' ',' ',' ',' ',' ',' ',' '},
        {' ',' ',' ',' ',' ',' ',' ',' ',' ',' '},
        {' ',' ',' ',' ',' ',' ',' ',' ',' ',' '},
        {' ',' ',' ',' ',' ',' ',' ',' ',' ',' '},
        {' ',' ',' ',' ',' ',' ',' ',' ',' ',' '}
    };

    // 预处理提取每行有效字符
    vector<vector<char>> valid_lines;
    for (int i = 0; i < rows; ++i) {
        vector<char> tmp;
        for (int j = 0; j < columns; ++j) {
            if (is_valid(arr[i][j])) {
                tmp.push_back(arr[i][j]);
            }
        }
        if (tmp.empty()) {
            // 若有效行可能中间夹空行,删除下面的break即可
            break;
        }
        valid_lines.push_back(tmp);
    }
    int max_word_len = valid_lines.size();

    // 逐长度生成并输出组合
    for (int len = 1; len <= max_word_len; ++len) {
        cout << "len : " << len << endl;
        vector<string> words = {""};
        for (int i = 0; i < len; ++i) {
            vector<string> new_words;
            for (const string& pre : words) {
                for (char c : valid_lines[i]) {
                    new_words.push_back(pre + c);
                }
            }
            words.swap(new_words);
        }
        for (const string& w : words) {
            cout << w << endl;
        }
    }
    return 0;
}
注意事项
  • 如果你的二维数组空白标识不是空格,只需要修改is_valid函数的判断逻辑即可。
  • 如果有效行中间可能存在全空的行,删除预处理部分的break语句,程序会自动跳过空行,只拼接有有效字符的行。
  • 当行数较多时组合数量会指数级增长,可根据实际需求添加结果过滤或者内存优化逻辑。

内容的提问来源于stack exchange,提问作者Danny G

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:39:03