【问题标题】:All combination (and not permutation) of a string in c#c#中字符串的所有组合(而不是排列)
【发布时间】:2015-08-10 16:10:07
【问题描述】:

我只想找到输入字符串的所有组合,所以如果我使用这个世界:“猫”,我想得到类似的东西:

c
a
t
ca
ct
ac
at
ta
tc
cat
cta
 ... etc

但不是

ccc
cca
... etc

我发现了很多类似的,但那些得到的排列与输入字符串一样长,或者它只是敲掉了一些。如果我有 4 个字符长的字符串,我如何让它给我 1、2 和 4 个字符的长字符串?

【问题讨论】:

  • @Whoever 投票决定关闭请求场外资源:原因错误。
  • 我会在 CodeProject 使用很棒的 Combinatorics Library。您的场景属于变化(即没有重复)类别。我个人在很多情况下都使用过这个库。

标签: c# string combinations


【解决方案1】:

其实这里有3个阶段:

  1. 从输入单词中选择字母。我通过使用提升的计数器来做到这一点,然后将其视为位表示,如果位 i'1',那么我选择字符 i时间>。如果 '0' 则不要。
  2. 根据选定的字母生成排列。这里我使用递归辅助函数Permutations
  3. 从最终结果中删除重复项。如果您的原始单词重复字符,可能会出现重复。例如:“猫”

解决方案

static void Main(string[] args)
{
    string word = "catt";

    List<string> result = new List<string>();

    int total = (int)Math.Pow(2, word.Length);


    for (int i = 0; i < total; i++)
    {
        string tempWord = string.Empty;
        // pick the letters from the word

        for (int temp = i, j = 0; temp > 0; temp = temp >> 1, j++)
        {
            if ((temp & 1) == 1)
            {
                tempWord += word[j];
            }
        }

        // generate permutations from the letters
        List<string> permutations;
        Permutations(tempWord, out permutations);

        foreach (var prm in permutations)
            result.Add(prm);
    }

    // remove duplicates
    var resultWithoutDuplicates = result.Distinct();

    foreach (var w in resultWithoutDuplicates)
        Console.WriteLine(w);


    Console.ReadLine();

}


static void Permutations(string str, out List<string> result)
{
    result = new List<string>();

    if (str.Length == 1)
    {
        result.Add(str);
        return;
    }


    for (int i = 0; i < str.Length; i++)
    {
        char c = str[i];
        string temp = str.Remove(i, 1);

        List<string> tempResult;
        Permutations(temp, out tempResult);

        foreach (var tempRes in tempResult)
            result.Add(c + tempRes);
    }
}

我们可以使用 hashset 代替 list,而不是执行最后一步(删除重复),以确保在将结果添加到最终数据结构期间没有重复。

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 2023-03-14
    相关资源
    最近更新 更多