我有一个数组,我需要所有可能的子数组(段或子序列),除了空子数组。这是而不是幂集,因为每个子数组只有输入数组中连续的元素。
例如,对于输入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语句的解决方案。
发布于 2019-05-08 18:50:16
假设您的源是一个List
(如果不是,请转换为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
通常是首选的。
发布于 2019-05-13 23:47:44
尽管NetMage的解决方案是正确的,但我最终还是编写了自己的扩展方法,它使用Array.Copy
来提高性能:
/// <summary>
/// Get all subsequences of the given sequence.
/// {1,2,3}=>{{1,2},{1,2,3},{2,3}}
/// </summary>
public static T[][] GetAllSubsequences<T>(this IEnumerable<T> collection)
{
var list = (collection as T[]) ?? collection.ToArray();
return list.SelectMany((x, i) => list.Skip(i).Select((z, j) =>
{
var arr = new T[j + 1];
Array.Copy(list, i, arr, 0, j + 1);
return arr;
})).ToArray();
}
https://stackoverflow.com/questions/56046975
复制相似问题