java字符串长度等于n,使用n个字符生成长度为l的所有可能字符串

您不必实施任何后续行动 . 您所要做的就是从上一个项目中获取下一个项目

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 -> ...

Code (C#) ;让我们概括解决方案(任何 alphabet 没必要 string )

// alphabet should contain distinct items

private static IEnumerable Solution(IEnumerable 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));

}

Demo:

// 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)));

Outcome:

aa, ab, ac, ba, bb, bc, ca, cb, cc

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值