输出"ABCDEF"每个字符的所有字符串的组合

 

  发布出来,做一个笔记

  思路:

  把"ABCDEF"看成一个字符数组,第一位“A”的位置有6种可能,排除第一位,第二位“B”的位置有5种可能……

  由此可知是递归加上循环,代码如下,第一种方法是for实现,第二种方法是linq实现的,但思路一样的。

 

方法一:

private static List<string> GetPattern(string source)
{
if (string.IsNullOrEmpty(source))
{
throw new Exception("source 不能为空");
}

if (source.Length == 1)
{
return new List<string> { source };
}

var firstChar = source.First();
var result = new List<string>();
foreach (var childen in GetPattern(source.Substring(1)))
{
for (int i = 0; i <= childen.Length; i++)
{
result.Add(childen.Insert(i, firstChar.ToString()));
}
}

return result;
}

方法二:

private static IEnumerable<string> GetCombination(string source)
{
if (string.IsNullOrEmpty(source))
{
throw new Exception("source 不能为空");
}

if (source.Length == 1)
{
return new List<string> { source };
}

return from child in GetCombination(source.Substring(1))
from i in Enumerable.Range(0, child.Length + 1)
let firstChar = source.Substring(0, 1)
select child.Insert(i, firstChar);
}

 

 

posted @ 2014-03-18 11:30  junjieok  阅读(926)  评论(0)    收藏  举报