將問題分爲兩部分:首先嚐試獲取具有不同字符的size
和alphabet
的所有排列,例如, C#代碼可以是:
private static IEnumerable<string> Permutations(int size, string alphabet) {
StringBuilder word = new StringBuilder(new string(alphabet[0], size));
while (true) {
string result = word.ToString();
yield return result;
if (result.All(c => c == alphabet[alphabet.Length - 1]))
break;
for (int i = word.Length - 1; i >= 0; --i)
if (result[i] == alphabet[alphabet.Length - 1])
word[i] = alphabet[0];
else {
word[i] = alphabet[alphabet.IndexOf(word[i]) + 1];
break;
}
}
}
測試:
// AA, AB, AC, BA, BB, BC, CA, CB, CC
Console.Write(string.Join(", ", Permutations(2, "ABC")));
然後結合不同size
S的排列在C#中implmentation它可以很容易地的LINQ的幫助下完成的情況下:
string alphabet = "ABA";
int limit = alphabet.Length; //TODO: it's unclear what limit is, put the right one
string distinctAlphabet = string.Concat(alphabet.OrderBy(c => c).Distinct());
var result = Enumerable.Range(1, limit)
.Select(length => string.Join("; ", Permutations(length, distinctAlphabet)));
Console.Write(string.Join(Environment.NewLine, result));
輸出(對於source = "ABC";
):
A; B; C
AA; AB; AC; BA; BB; BC; CA; CB; CC
AAA; AAB; AAC; ABA; ABB; ABC; ... ; CBB; CBC; CCA; CCB; CCC
(用於source = "ABA";
)輸出:
A; B
AA; AB; BA; BB
AAA; AAB; ABA; ABB; BAA; BAB; BBA; BBB
你應該澄清 '等' 的一部分。沒有最大尺寸,就有無數的組合。 –
@huck_cussler,我想現在我想要得到程序的主要邏輯,所以它受到ABC長度的限制,但是在將來我想添加一個實現來打印所有長度限制的組合。 – user264307
如果輸入是'AAB',你會怎麼做? – stark