用遞歸能實現一個數組劃分的算法麼?
給一個數組,長度為m,劃分成n個子數組(每個數組起碼有一個元素),比如
{1 2 3 4 5}劃分成2個:
1, 2345 12,345 123,45 1234,5一共5個分法
{1234}分成3個
1,2,34 1,23,4 12,3,4,一共3個分法
求代碼怎麼寫
IEnumerable<IEnumerable<IEnumerable<int>>> Split(IEnumerable<int> source, int n)
{
int[] splitter = Enumerable.Range(1, n - 1).ToArray();
splitter[n - 2]--;
int[] lastsp = Enumerable.Range(source.Count() - n, n -1).ToArray();
while (splitter.Zip(lastsp, (x, y) => x != y).Any(x => x == true))
{
for (int i = n - 2; i >= 0; i--)
{
if (splitter[i] < lastsp[i])
{
splitter[i]++;
for (int j = i + 1; j < n - 1; j++)
{
splitter[j] = splitter[i] + j - i;
}
break;
}
}
IEnumerable<int>[] result = new IEnumerable<int>[n];
int acc = 0;
for (int i = 0; i < n; i++)
{
if (i == n - 1)
{
result[i] = source.Skip(acc);
}
else
{
result[i] = source.Skip(acc).Take(splitter[i] - acc);
acc = splitter[i];
}
}
yield return result;
}
}