这是一个生成所有可能的断点组合的函数,你可以将它们存储在一个列表中而不是打印它们,然后统一选择其中一个:
static void breakpointCombinations(List<int> possiblePositions, List<int> breakpointCombination, int remainingBreakpoints, int minSpace, int currentPos)
{
if (remainingBreakpoints == 0)
{
foreach (int tempPos in breakpointCombination)
{
Console.Write(tempPos + " ");
}
Console.WriteLine();
}
else if (remainingBreakpoints * minSpace > possiblePositions.Count - currentPos)
return;
else
{
if (currentPos >= minSpace - 1)
{
breakpointCombination.Add(possiblePositions[currentPos]);
breakpointCombinations(possiblePositions, breakpointCombination, remainingBreakpoints - 1, minSpace, currentPos + minSpace);
breakpointCombination.Remove(possiblePositions[currentPos]);
}
breakpointCombinations(possiblePositions, breakpointCombination, remainingBreakpoints, minSpace, currentPos + 1);
}
}
对函数的调用(在此示例中,10 个元素,2 个断点,最小空间为 2):
static void Main(string[] args)
{
List<int> Positions = new List<int>();
for (int i = 0; i < 10; i++)
{
Positions.Add(i);
}
breakpointCombinations(Positions, new List<int>(), 2, 2, 0);
}
从您的示例中暗示,空格 2 意味着在 2 个断点之间应该至少有一个位置(例如,这意味着 [2, 4] 是合法的),我从头到尾处理相同的空格(这在示例中不一致),这意味着如果元素是 [0, ... ,9],则第一个合法断点位于元素 1,最后一个合法断点位于元素 8。