需要递归函数来生成唯一的字符串组合

时间:2009-02-07 10:48:36

标签: c# function recursion

我从数据库(A,B,C,D,E,F,G,H)中获得了一些(比如9,没有不确定的)唯一字符串,我想创建这些字段的唯一组合来填充列表框所以用户可以选择这些字符串字段的单个或不同组合 喜欢 A,B,C,d,E,F,G,H, AB,AC,AD,AE,AF,AG,AH,AC,AD,AE,AF,AG,AG,AH,... ABC,ABD,ABE,ABF,ABG,ABH,ACD,ACE,ACF,ACG,ACH,.....

在C#中(获胜申请) 提前致谢

3 个答案:

答案 0 :(得分:8)

我的第一选择是“使用CheckedListBox并让用户自己选择” - 这将拯救他们的理智......你想在长名单中寻找“ABCEFH”吗?)。

如果你想要字符串: 如何使用二进制算术?即使用一个数字(根据元素数量的位长),并简单地保持递增,包括每次设置位?所以在C#中,例如:

static void Main()
{
    foreach (string value in GetCombinations(
        "A", "B", "C", "D", "E", "F", "G", "H"))
    {
        Console.WriteLine(value);
    }
}
static IEnumerable<string> GetCombinations(params string[] tokens)
{
    ulong max = (ulong) 1 << tokens.Length;
    StringBuilder builder = new StringBuilder();
    // test all bitwise combinations
    for (ulong value = 0; value < max; value++)
    {
        builder.Length = 0;
        ulong tmp = value;
        // include the tokens for the set bits
        for (int i = 0; i < tokens.Length; i++)
        {
            if ((tmp & (ulong)1) == 1) builder.Append(tokens[i]);
            tmp >>= 1;
        }
        yield return builder.ToString();
    }
}

如果您希望按照示例的顺序输入数据,那么LINQ很有用:

    foreach (string value in GetCombinations(
          "A", "B", "C", "D", "E", "F", "G", "H")
        .OrderBy(s=>s.Length)
        .ThenBy(s=>s))
    {
        Console.WriteLine(value);
    }

答案 1 :(得分:1)

公共班级组合 {     static int count = 0;

public static void main(String[] args)
{
    StringBuilder out = new StringBuilder("");
    StringBuilder str = new StringBuilder("aabcbd");

    combination(str, out, 0);
    System.out.println("The Count : " + count);
}


// Recursive
static void combination(StringBuilder in, StringBuilder out, int start)
{
    int len = in.length();

    for (int i = start; i < len; i++)
    {
        if (isAppended(in, out, i))
        {
            continue;
        }

        out.append(in.charAt(i));
        count++;
        System.out.println(out);
        combination(in, out, i + 1);
        out.deleteCharAt(out.length() - 1);
    }
}


static boolean isAppended(StringBuilder in, StringBuilder out, int index)
{
    int inCount = 0;
    int outCount = 0;

    int i = 0;
    int len = out.length();
    char ch = in.charAt(index);

    for (i = 0; i < index; i++)
    {
        if (in.charAt(i) == ch)
        {
            inCount++;
        }
    }

    for (i = 0; i < len; i++)
    {
        if (out.charAt(i) == ch)
        {
            outCount++;
        }
    }

    if (inCount != outCount)
    {
        return true;
    }

    return false;
}

}

答案 2 :(得分:0)

这就像计算基数'n'中的整数一样..应该不难。