【问题标题】:Get all possible word combinations获取所有可能的单词组合
【发布时间】:2011-05-16 12:12:22
【问题描述】:

我有一个包含 n 个单词的列表(比如说 26 个)。现在我想获取所有可能组合的列表,但每行最多 k 个单词(比如说 5 个)

所以当我的单词列表是:aaa, bbb, ..., zzz 我想得到:

aaa
bbb
...
aaabbb
aaaccc
...
aaabbbcccdddeeefff
aaabbbcccdddeeeggg
...

我想让它可变,以便它可以与任何 n 或 k 值一起使用。 不应该有两次,每个组合都需要采取(即使有很多)。

我怎样才能做到这一点?

编辑:

感谢您的回答。这不是一项任务。只是我忘记了密码的组合,我想确保我已经测试了所有组合。虽然我没有 26 个密码部分,但这让我更容易解释我想要什么。

如果有其他人有同样的问题,这个链接可能会有所帮助:
Generate word combination array in c#

【问题讨论】:

标签: c# recursion combinatorics combinations


【解决方案1】:

我写了一个简单的函数来做到这一点

        private string allState(int index,string[] inStr)
        {
            string a = inStr[index].ToString();
            int l = index+1;
            int k = l;
            var result = string.Empty;
            var t = inStr.Length;
            int i = index;
            while (i < t)
            {
                string s = a;
                for (int j = l; j < k; j++)
                {
                    s += inStr[j].ToString();
                }
                result += s+",";
                k++;
                i++;
            }

            index++;
            if(index<inStr.Length)
                result += allState(index, inStr);
            return result.TrimEnd(new char[] { ',' });
        }

allState(0, new string[] { "a", "b", "c"})

【讨论】:

  • 不幸的是,这仅适用于 3 个字符串的列表。任何更大的东西都会开始丢失组合。 IE: ABCD 会给你 ABCD, ABC, BCD 但它不会给你 ACD
【解决方案2】:

你可以看看this

但是,如果您需要获得大量组合(数千万),您应该使用惰性求值来生成组合。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-26
    • 2013-10-06
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多