c# 中字符串的所有组合(而不是排列)

All combination (and not permutation) of a string in c#

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

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

但不是

ccc
cca
... etc

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

实际上你有3个阶段:

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

解决方案:

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,而不是执行最后一步(删除重复),以确保在将结果添加到最终数据结构期间没有重复。

希望对您有所帮助。