Вам не нужно реализовывать рекурсию.Все, что вам нужно сделать, это получить следующий предмет из предыдущего
aa -> ab -> ac -> : we can't add 1 to c so why reset the last 'c' to 'a'
but add 1 to previous 'a': 'ba'
now we keep on adding one to the last 'a':
ba -> bb -> bc -> : again we reset 'c' to 'a' and increment previous b
ca -> ...
Код (C #) ;давайте обобщим решение (любое alphabet
необязательно string
)
// alphabet should contain distinct items
private static IEnumerable<T[]> Solution<T>(IEnumerable<T> alphabet, int length) {
if (null == alphabet)
throw new ArgumentNullException(nameof(alphabet));
var chars = alphabet.Distinct().ToArray();
if (length <= 0 || chars.Length <= 0)
yield break;
int[] result = new int[length];
do {
yield return result
.Select(i => chars[i])
.ToArray();
for (int i = result.Length - 1; i >=0 ; --i)
if (result[i] == chars.Length - 1)
result[i] = 0;
else {
result[i] += 1;
break;
}
}
while (!result.All(item => item == 0));
}
Демо:
// Or var test = Solution("abc", 2);
var test = Solution(new char[] { 'a', 'b', 'c' }, 2);
var report = string.Join(", ", test
.Select(item => string.Concat(item)));
Итог:
aa, ab, ac, ba, bb, bc, ca, cb, cc