自己在一个搜索程序中遇到了这样一个问题:怎么从数组(集合)中返回指定长度的子数组(集合)。比如数组{1,2,3,4},现在要返回所有长度为n=2的子数组,即{1,2}{1,3}{1,4}{2,3}{2,4}{3,4}。如果这个n在写代码时就确定,那就用n层循环可以很简单的实现。但是,关键在于n是在程序运行时才知道的,这样就不能只能用循环了。
想了几天后,才完全实现了这个功能。

Code
1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Linq.Expressions;
5
using System.Text;
6
using System.Runtime.InteropServices;
7
using System.Drawing;
8
using System.Diagnostics;
9
using System.Threading;
10
using System.IO;
11
using System.Runtime.Serialization;
12
using System.Runtime.Serialization.Formatters.Binary;
13
14
15
namespace ConsoleApplication1
16

{
17
class Program
18
{
19
static void Main(string[] args)
{
20
//要操作的集合
21
List<int> array = new List<int>();
22
for (int i = 1; i <= 8; i++)
{
23
array.Add(i);
24
}
25
//结果集合
26
List<List<int>> result = Cal(array, 2);
27
28
for (int i = 0; i < result.Count; i++)
{
29
for (int j = 0; j < result[i].Count; j++)
{
30
Console.Write(result[i][j] + " ");
31
}
32
Console.WriteLine();
33
}
34
35
Console.WriteLine(result.Count);
36
Console.ReadKey();
37
}
38
//
39
static List<List<int>> Cal(List<int> array, int n)
{
40
List<List<int>> result = new List<List<int>>();
41
List<int> one = new List<int>();
42
43
for (int i = 0; i < array.Count; i++)
{
44
one.Add(array[i]);
45
Add(array.GetRange(i + 1, array.Count - 1 - i), n - 1, result, one);
46
if (one.Count != 0)
47
one.RemoveAt(one.Count - 1);
48
//这里很可以用one.Clear();
49
//循环完一次后,就可以清除one,然后再重新开始
50
}
51
return result;
52
}
53
//用于递归的函数
54
static void Add(List<int> array, int n, List<List<int>> result, List<int> one)
{
55
//如果n=0,就表明one的Count属性已等于n
56
if (n == 0)
{
57
result.Add(Clone(one) as List<int>);
58
//进行下一次之前,移除最后一个元素
59
one.RemoveAt(one.Count - 1);
60
}
61
else
{
62
for (int i = 0; i < array.Count; i++)
{
63
one.Add(array[i]);
64
//在这里进行递归,同时n-1
65
Add(array.GetRange(i + 1, array.Count - 1 - i), n - 1, result, one);
66
}
67
//一轮结束后,移除最后一个元素
68
one.RemoveAt(one.Count - 1);
69
}
70
}
71
//用来复制对象的函数
72
public static object Clone(object obj)
{
73
using (MemoryStream ms = new MemoryStream())
{
74
IFormatter formattor = new BinaryFormatter();
75
formattor.Serialize(ms, obj);
76
ms.Seek(0, SeekOrigin.Begin);
77
return formattor.Deserialize(ms);
78
}
79
}
80
81
}
82
}
上面的算法,用到了递归,关键在于设置了一个临时变量List<int> one,每递归一个就在one中添加一个元素,直到one的Count==n。
这是自己的想法,这个题目应该是很简单的,不知道有没有高手给出更简单的答案!!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?