C# 通过一个数组穷举所有可能的组合
比如我数组元素是a,b,c,d,e那么生成的列表是:abcdea,ba,ca,da,eb,cb,db,ec,dc,ed,ea,b,ca,b,da,b,ea,c,da,c,...
比如 我数组元素是 a,b,c,d,e
那么生成的列表是:
a
b
c
d
e
a,b
a,c
a,d
a,e
b,c
b,d
b,e
c,d
c,e
d,e
a,b,c
a,b,d
a,b,e
a,c,d
a,c,e
a,d,e
b,c,d
b,c,e
b,d,e
c,d,e
a,b,c,d
a,b,c,e
a,b,d,e
a,c,d,e
b,c,d,e
a,b,c,d,e
。。。总之能生成所有不重复的组合 展开
那么生成的列表是:
a
b
c
d
e
a,b
a,c
a,d
a,e
b,c
b,d
b,e
c,d
c,e
d,e
a,b,c
a,b,d
a,b,e
a,c,d
a,c,e
a,d,e
b,c,d
b,c,e
b,d,e
c,d,e
a,b,c,d
a,b,c,e
a,b,d,e
a,c,d,e
b,c,d,e
a,b,c,d,e
。。。总之能生成所有不重复的组合 展开
1个回答
展开全部
以前写过,代码找不到了,又重新写一遍。。要用递归去做
class Arrange
{
private char[] _chars;
public Arrange(char[] chars)
{
if (chars == null || chars.Length == 0)
{
throw new Exception("传入的字符数组不能为空");
}
_chars = chars.Distinct().ToArray();
}
public List<String> GetAllArrangements()
{
List<String> returnValue = new List<string>();
for (int i = 0; i < _chars.Length; i++)
{
returnValue.AddRange(GetArrangements("", i + 1));
}
return returnValue;
}
private List<String> GetArrangements(String s, int length)
{
if (length == 0)
{
return new List<string> { s };
}
List<String> returnValue = new List<String>();
for (int i = 0; i < _chars.Length; i++)
{
String newS = s + _chars[i];
List<String> nextArray = GetArrangements(newS, length - 1);
returnValue.AddRange(nextArray);
}
return returnValue;
}
}
调用结果:
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询