我有一个数组,我需要所有可能的子数组(段或子序列),但空的除外。这不是幂集,因为每个子数组只有在输入数组中连续的元素。
例如,对于 input new int[]{1,2,3}
,输出将是:
new int[]{
new int[]{1},
new int[]{1,2},
new int[]{1,2,3},
new int[]{2},
new int[]{2,3},
new int[]{3}
}
请注意,这{1,3}
不存在,因为我不想要所有子集(幂集),只想要所有子序列。
我更喜欢使用单个 LINQ 语句的解决方案。
假设您的来源是 a List
(如果不是,则转换为 a List
),那么您可以执行以下操作:
var srcl = src.ToList();
var ans = Enumerable.Range(0, srcl.Count).SelectMany(start => Enumerable.Range(1, srcl.Count-start).Select(count => srcl.GetRange(start, count)));
使用自然ArraySegment
扩展:
public static class ArrayExt {
public static IEnumerable<T> Segment<T>(this T[] src, int start, int count) => new ArraySegment<T>(src, start, count);
}
你可以让它返回一个数组数组:
var ans = Enumerable.Range(0, src.Length).SelectMany(start => Enumerable.Range(1, src.Length-start).Select(count => src.Segment(start, count).ToArray()));
但List
通常是首选。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句