1234数字排列组合成不同的三位数,用c#如何编写
时间: 2024-04-15 20:29:14 浏览: 11
你可以使用循环嵌套来实现数字排列组合。下面是一个使用 C# 编写的示例代码,它将生成所有不同的三位数排列组合:
```csharp
using System;
class Program
{
static void Main(string[] args)
{
int[] nums = { 1, 2, 3, 4 };
GeneratePermutations(nums, 0, nums.Length - 1);
}
static void GeneratePermutations(int[] nums, int start, int end)
{
if (start == end)
{
Console.WriteLine(string.Join("", nums));
}
else
{
for (int i = start; i <= end; i++)
{
Swap(ref nums[start], ref nums[i]);
GeneratePermutations(nums, start + 1, end);
Swap(ref nums[start], ref nums[i]);
}
}
}
static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
}
```
运行此代码,它将输出所有不同的三位数排列组合,例如:
```
123
124
132
134
142
143
213
214
231
234
241
243
312
314
321
324
341
342
412
413
421
423
431
432
```
这里使用了递归函数 `GeneratePermutations` 来生成排列组合,`Swap` 函数用于交换数组中的两个元素。