我找到的最接近的SO主题在这里:列出字符串/整数的所有排列
但是,对于字符串中每个位置的不同字符集,我将如何使用呢?
一个示例:我将字符串长度指定为“ 3”。前两个位置应为“ a”或“ b”,但最后一个位置应为“ 1”或“ 2”,例如:
aa1 ba1 ab1 bb1 aa2 ab2 ba2 bb2
使用此代码:
public static List<string> GenerateCombinations(char[][] characters) { var combinations = new List<string>(); GenerateCombinations(0, characters, new char[characters.GetLength(0)], combinations); return combinations; } private static void GenerateCombinations(int level, char[][] characters, char[] current, List<string> combinations) { if (level == characters.GetLength(0)) { combinations.Add(new string(current)); return; } foreach (var character in characters[level]) { current[level] = character; GenerateCombinations(level + 1, characters, current, combinations); } }
使用示例:
public static void Main() { var characters = new[] { new[] { 'a', 'b' }, new[] { 'a', 'b' }, new[] { '1', '2' } }; var combinations = GenerateCombinations(characters); foreach (var combination in combinations) { Console.WriteLine(combination); } }
输出:
aa1 aa2 ab1 ab2 ba1 ba2 bb1 bb2