我想要一个不先计算所有内容然后排序的答案,同时仍然只通过最少的时间处理事情。这就是我所拥有的。请注意,从外部修改int[]
可能会搞砸结果(或者,可能会返回 a new int[]
)。
第一个方法告诉辅助方法它想要输出多少个 0。助手然后计算结果,如果它不能填充足够的 0 或者如果它遍历所有数据则停止。
static IEnumerable<int[]> Permutation(int[] bounds)
{
for(int num0s = bounds.Length; num0s >= 0; --num0s)
{
foreach(int[] ret in PermHelper(num0s, 0, bounds, new int[bounds.Length]))
yield return ret;
}
}
static IEnumerable<int[]> PermHelper(int num0s, int index, int[] bounds, int[] result)
{
//Last index.
if(index == bounds.Length - 1)
{
if(num0s > 0)
{
result[index] = 0;
yield return result;
}
else
{
for(int i = 1; i < bounds[index]; ++i)
{
result[index] = i;
yield return result;
}
}
}
//Others.
else
{
//still need more 0s.
if(num0s > 0)
{
result[index] = 0;
foreach(int[] perm in PermHelper(num0s - 1, index + 1, bounds, result))
yield return perm;
}
//Make sure there are enough 0s left if this one isn't a 0.
if(num0s < bounds.Length - index)
{
for(int i = 1; i < bounds[index]; ++i)
{
result[index] = i;
foreach(int[] perm in PermHelper(num0s, index + 1, bounds, result))
yield return perm;
}
}
}
}