如果顺序无关紧要,您可以尝试Linq。我们枚举范围内的所有二进制数[0..2**word.Length]
。并将每个数字视为掩码:0
- 小写,1
- 大写。例如happy
我们有
mask string
----------------
00000 -> happy
00001 Happy
00010 hAppy
00011 HAppy
00100 haPpy
00101 HaPpy
...
11111 HAPPY
代码:
using System.Linq;
...
List<string> permutate(string word) =>
Enumerable
.Range(0, 1 << word.Length)
.Select(mask => string.Concat(word.Select((c, i) => (mask & (1 << i)) == 0
? char.ToLower(c)
: char.ToUpper(c))))
.ToList();
演示:
Console.Write(string.Join(", ", permutate("happy")));
结果:
happy, Happy, hAppy, HAppy, haPpy, HaPpy, hAPpy, HAPpy, hapPy, HapPy, hApPy, HApPy, haPPy, HaPPy, hAPPy, HAPPy, happY, HappY, hAppY, HAppY, haPpY, HaPpY, hAPpY, HAPpY, hapPY, HapPY, hApPY, HApPY, haPPY, HaPPY, hAPPY, HAPPY