列出不同字符组合的排列 [英] Listing permutations of different combination of characters
本文介绍了列出不同字符组合的排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这里找到最接近的SO主题:列出字符串的所有排列/整数
The closest SO topic I found is here: Listing all permutations of a string/integer
但是我将如何针对字符串中每个位置的不同字符集使用此功能呢?
But how would I make use of this for different sets of characters for each position in a string?
一个示例:我将字符串长度指定为"3".前两个位置应该是"a"或"b",但最后一个位置应该是"1"或"2",例如:
An example: I specify a string length of "3". The first two position should be either "a" or "b", but the last position should be either "1" or "2", e.g:
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
这篇关于列出不同字符组合的排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文