我有一系列0-9的数字。每个数字代表一个带有x和y坐标的位置。因此,位置0可以表示(5,5)或类似的东西,总是(x,y)。现在我需要做的是使用5个位置递归地击打每个可能的路线以获得用户给出的位置。例如:
Input = (1, 2) //This is the co-ordinate the user gives.
现在给出这个输入它应该采取每个可能的路径并找到最短的路径。一些路径可能是:
start 0 1 2 3 4 input
start 0 1 2 3 5 input
start 0 1 2 3 6 input
start 0 1 2 3 7 input
start 0 1 2 4 3 input
start 1 0 2 3 5 input
and so on....
它可以是0-9中5个数字的任意组合。它必须在输入目的地结束并从起始目的地开始。数字不能重复使用。所以我需要递归地添加给定课程的所有距离(例如,开始0 1 2 3 4输入),并在经历这5个点时找到最短的路线。
问题:基础和递归案例是什么?
答案 0 :(得分:1)
基本上你要做的是从集合{1,..,n}生成大小为k(路径长度)的所有组合,然后计算它的路径值。
这是一个C#代码示例:
void OPTPathForKSteps(List<int> currentPath, List<int> remainingPositions, int remainingSteps)
{
if (remainingSteps == 0)
{
// currentPath now contains a combination of k positions
// do something with currentPath...
}
else
{
for (int i = 0; i < remainingPositions.Count; i++)
{
int TempPositionIndex = remainingPositions[i];
currentPath.Add(TempPositionIndex);
remainingPositions.RemoveAt(i);
OPTPathForKSteps(currentPath, remainingPositions, remainingSteps - 1);
remainingPositions.Insert(i, TempPositionIndex);
currentPath.RemoveAt(currentPath.Count - 1);
}
}
}
这是函数的初始调用(假设Positions是0 ... n位置的整数列表,k是路径的长度):
OPTPathForKSteps(new List<int>(), Positions, K);
您可以更改函数并添加参数,以便返回最佳路径和最小值。 还有其他(可能更短)的方法来创建这些组合,我的实现的好处是它在内存上很轻,并且不需要存储所有可能的组合。