C#排列组合的代码
最近试了几题leetcode,有必要复习排列组合的写法
组合:
/// <summary>
///
/// </summary>
/// <param name="source">待选区域,这里假设为char序列</param>
/// <param name="index">开始的下标,初始为0</param>
/// <param name="buff">目标的存放</param>
/// <param name="level">当前的级别,初始为0</param>
/// <param name="list">返回值</param>
void GetLetter(string source, int index, int[] buff, int level, List<string> list)
{
if (level == buff.Length)
{
StringBuilder sb = new StringBuilder();
foreach (int i in buff)
//如果是电话号码按键这种组合方式,for( int index ...) 再根据buff[index]的值选择source里的具体内容,因此类似写法为source[index][buff[index]]
sb.Append(source[i]);
list.Add(sb.ToString());
return;
}
//每一轮的选择,如果可以重复,则下标从0开始
//如果不能重复,则跳过之前已经选的内容,下标从index开始
//如果是电话号码按键这种组合方式,则source本身为二维数组,当前的来源为source[level],而且明显要遍历所有可能,index从0开始
for (int i = index; i < source.Length; i++)
{
buff[level] = i;
GetLetter(source, i + 1, buff, level + 1, list);
}
}
排列,参考了巧妙的swap构成排列
/// <summary>
///
/// </summary>
/// <param name="source">待选来源</param>
/// <param name="start">下标,初始为0</param>
/// <param name="list"></param>
void GetLetter(int[] source, int start, List<string> list)
{
if (start == source.Length)
{
StringBuilder sb = new StringBuilder();
foreach (int i in source)
sb.Append(i);
list.Add(sb.ToString());
return;
}
for (int i = start; i < source.Length; i++)
{
swap(source, start, i);
GetLetter(source, start + 1, list);
swap(source, start, i);
}
}
void swap(int[] source, int s , int e )
{
int t = source[s];
source[s] = source[e] ;
source[e] = t;
}
以上是 C#排列组合的代码 的全部内容, 来源链接: utcz.com/z/516328.html