排列组合

cpfxs 2012-10-09 08:08:00
假设:1,2,3,4,5 五个数字选3组合

我只会得到 123,124,125,134,135,145,234,235,245,345的10种组合

那把这10个组合再排列
比如: 123 得到321、312、213、231,132,123六个组合
245 得到524、542、425、452、254、245六个组合
... ...

10*6 = 60个

谢谢
...全文
110 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
cpfxs 2012-10-10
  • 打赏
  • 举报
回复
谢谢,不过这个方法好复杂,我自己想出来了
threenewbee 2012-10-09
  • 打赏
  • 举报
回复
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string s = "12345";
List<string> list = new List<string>();
foreach (var i in Combo(s, 3))
{
list = list.Union(Arrange(i)).ToList();
}
Console.WriteLine("count: " + list.Count);
list.ForEach(x => Console.WriteLine(x));
}


static IEnumerable<string> Arrange(string source)
{
for (int i = 0; i < source.Length; i++)
{
if (source.Length == 1)
{
yield return source;
}
else
{
foreach (var x in Arrange(source.Substring(0, i) + source.Substring(i + 1)))
{
yield return source[i] + x;
}
}
}
}

static IEnumerable<string> Combo(string source, int len)
{
int[] pos = new int[len];
for (int i = 0; i < len; i++) pos[i] = i;
while (pos[0] < source.Length - len)
{
string str = "";
for (int i = 0; i < len; i++) str += source[pos[i]];
for (int i = len - 1; i >= 0; i--)
{
if (pos[i] < source.Length - len + i)
{
pos[i]++;
for (int j = i + 1; j <= len - 1; j++)
{
pos[j] = pos[i] + j - i;
}
break;
}
else
{
continue;
}
}
yield return str;
}
yield return source.Substring(source.Length - len);
}
}
}

count: 60
123
132
213
231
312
321
124
142
214
241
412
421
125
152
215
251
512
521
134
143
314
341
413
431
135
153
315
351
513
531
145
154
415
451
514
541
234
243
324
342
423
432
235
253
325
352
523
532
245
254
425
452
524
542
345
354
435
453
534
543
Press any key to continue . . .

110,825

社区成员

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

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

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