谁帮我把这三层循环变成递归?

qtanchun 2012-09-07 09:42:40

private StringBuilder s = new StringBuilder();
List<int> source = ReadParam();
foreach (var i in source)
{
foreach (var j in source)
{
foreach (var k in source)
{
s.AppendFormat("{0}", ((char)i).ToString());
s.AppendFormat("{0}", ((char)j).ToString());
s.AppendFormat("{0}", ((char)k).ToString());
s.Append("\r\n");
}
}
}

谁帮我把这三层循环变成递归?
...全文
169 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
h422274755 2012-09-07
  • 打赏
  • 举报
回复


Fun(0,0);
public void Fun( int i,int j)
{
for (int k = 0; k < source.Count; k++)
{
s.AppendFormat("{0}", ((char)i).ToString());
s.AppendFormat("{0}", ((char)j).ToString());
s.AppendFormat("{0}", ((char)k).ToString());
s.Append("\r\n");
}
j++;

if (j < source.Count)
{
Fun(i, j);
}
else
{
i++;
if (i < source.Count)
{
j = 0;
Fun(i, j);
}
}
}
h422274755 2012-09-07
  • 打赏
  • 举报
回复
递归得用for循环。应该符合你的要求。
Fun(0,0);

public void Fun( int i,int j)
{
for (int k = 0; k < source.Count; k++)
{
s.AppendFormat("{0}", ((char)i).ToString());
s.AppendFormat("{0}", ((char)j).ToString());
s.AppendFormat("{0}", ((char)k).ToString());
s.Append("\r\n");
}
j++;

if (j < source.Count)
{
Fun(i, j);
}
else
{
i++;
if (i < source.Count)
{
j = 0;
Fun(i, j);
}
}
}
qtanchun 2012-09-07
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 的回复:]

http://blog.csdn.net/happy09li/article/details/7715858
[/Quote]


谢谢,我看下。
qtanchun 2012-09-07
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]

你这类似排列组合给你个参考,自己体会http://www.cnblogs.com/rogerwei/archive/2010/11/18/1880336.html
[/Quote]
谢谢,我看看。
qtanchun 2012-09-07
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

不知道你要干什么,,为什么要那样写?
直接这样就可以了,,

C# code
private StringBuilder s = new StringBuilder();
List<int> source = ReadParam();
foreach (var i in source)
{
……
[/Quote]
你这个只有一轮,只是把这个数组遍历了一遍,而我的要求是:任意取这个数组中一个值,组成三位的字符串。
比如source内容是{1,2,3},我要取的是"111"、"112","113","121","122",.......
sunylf 2012-09-07
  • 打赏
  • 举报
回复
這個用遞歸實行有點困難.i,j的值要保留.
bdmh 2012-09-07
  • 打赏
  • 举报
回复
你这类似排列组合给你个参考,自己体会http://www.cnblogs.com/rogerwei/archive/2010/11/18/1880336.html
熙风 2012-09-07
  • 打赏
  • 举报
回复
不知道你要干什么,,为什么要那样写?
直接这样就可以了,,

  private StringBuilder s = new StringBuilder();
List<int> source = ReadParam();
foreach (var i in source)
{
s.AppendFormat("{0}", ((char)i).ToString());
s.Append("\r\n");
}

111,120

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧