【发布时间】:2020-10-05 15:11:46
【问题描述】:
问题可能在其他地方被问到,但我找不到解决问题的方法。问题不是特定于语言的,可以在 python 中提出同样的问题。任务是生成字符串列表的算法,如Enumerable.Range,但字符不仅限于 1、2、3...,还可以是任何字符序列。最简单的示例是:
测试用例 1:
输入:
baseChars: ['a','b'],
所需字符串长度:2
输出:
['aa','ab','ba','bb']
测试用例 2:
baseChars: ['a','b']
所需字符串长度:1
输出:
['a','b']
功能运行良好:
static IList<string> baseChars = new List<string>() { "0", "1", "2", "3" };
static void CharsRange1(string prefix, int pos)
{
if (pos == 1)
{
foreach (string s in baseChars)
{
Console.WriteLine(prefix + s);
}
}
else
{
foreach (string s in baseChars)
{
CharsRange1(prefix + s, pos - 1);
}
}
}
预期和实际输出(用逗号替换换行符以节省空间):
000, 001, 002, 003, 010, 011, 012, 013, 020, 021, 022, 023, 030, 031, 032, 033, 100, 101, 102, 103, 110, 111, 112, 113, 120, 121, 122, 123, 130, 131, 132, 133, 200, 201, 202, 203, 210, 211, 212, 213, 220, 221, 222、223、230、231、232、233、300、301、302、303、310、311、312、313、 320、321、322、323、330、331、332、333
问题是把这个函数封装成一个库,所以返回类型应该是IEnumerable<string>,这样即使输入很大,内存也不会爆炸。但我的代码无法返回任何内容:
static IEnumerable<string> CharsRange2(string prefix, int pos)
{
if (pos == 1)
{
foreach (string s in baseChars)
{
yield return prefix + s;
}
}
else
{
foreach (string s in baseChars)
{
// here if i yield return then won't compile
// i thought at the end of recursive loop it will return
CharsRange2(prefix + s, pos - 1);
}
}
}
主要:
static void Main(string[] args)
{
//CharsRange1("", 3);//working
foreach (string s in CharsRange2("", 3))
{
Console.WriteLine(s);//nothing
}
Console.WriteLine("end");
Console.ReadKey();
}
有人可以帮忙吗?我已将我的代码放入github。如果您可以将我的实现更改为非递归但保留函数返回类型,也很高兴。
【问题讨论】:
-
CharsRange2(prefix + s, pos - 1);所以你递归调用函数,嗯,忽略结果?我怀疑你的意思是foreach并使用yield return。 -
您的问题描述也不是很好 - 因为您没有显示给定输入集的预期结果。我认为我了解您要做什么,但不是 100% 确定...
-
与第一个bing.com/search?q=c%23+recursive+yield+return 结果stackoverflow.com/questions/2055927/… 相比,显示的代码非常混乱。您能否检查您的代码并确保它有意义...
-
旁注:以任意基数计数确实是非常常见的竞争任务......这似乎是您要问的。您可能还想通过您的编辑来澄清这一点(或者澄清您想要的序列类型,如果它不计数)。
-
A (yield) return 只返回给直接调用者,而不是第一次调用递归链的人
标签: c# algorithm recursion permutation yield