我已经解决了下面显示的算法。
public static long park(int n)
{
// precondition: n >= 1
// postcondition: Return the number of ways to park 3 vehicles,
// designated 1, 2 and 3 in n parking spaces, without leaving
// any spaces empty. 1 takes one parking space, 2 takes two spaces,
// 3 takes three spaces. Each vehicle type cannot be distinguished
// from others of the same type, ie for n=2, 11 counts only once.
// Arrangements are different if their sequences of vehicle types,
// listed left to right, are different.
// For n=1: 1 is the only valid arrangement, and returns 1
// For n=2: 11, 2 are arrangements and returns 2
// For n=3: 111, 12, 21, 3 are arrangements and returns 4
// For n=4: 1111,112,121,211,22,13,31 are arrangements and returns 7
if(n==1)
{ return 1; }
else if(n==2)
{ return 2; }
else if(n==3)
{ return 4; }
else
{
return (park(n-1) + park(n-2) + park(n-3));
}
}我需要帮助的是找出一个后续问题,即在排列中包含空的停车位。这应该是递归解决的。
Let's designate a single empty space as E.
For n=1: 1,E and returns 2
For n=2: 11,2,EE,1E,E1 and returns 5
For n=3: 111,12,21,3,EEE,EE1,E1E,1EE,11E,1E1,E11,2E,E2 and returns 13
For n=4: there are 7 arrangements with no E, and 26 with an E, returns 33我在这上面花了很多时间。我从上面的算法中知道有多少排列没有空格。所以我一直在尝试找出有多少个排列有1个或更多的空格。这两个集合的结合应该会给我答案。对于n,具有一个或多个空空间的单空间排列的数量是2^n-1。但我不认为这会在递归解决方案中对我有帮助。
任何指导都将不胜感激。
发布于 2011-09-16 17:43:21
我认为这是可行的:
public static long park(int n)
{
if(n==1)
{ return 2; }
else if(n==2)
{ return 5; }
else if(n==3)
{ return 13; }
else
{
return (park(n-1) + park(n-1) + park(n-2) + park(n-3));
}
}发布于 2011-09-16 18:16:43
为了简单起见,我将使用递归来解释N<3中哪里出了问题。
对于一个空间,有两种情况,E和1,所以当n=1时,它应该是2。
当它是2时,它应该返回1+ park(1) + park(1),因为2是2,1E,E1,11,当它是2时仍然可以。
当它为3时,它应该返回1+ park(2) + park(1) + park(1),但是您可以看到,在park(1) + park(2)和Park(2) + park(1)中会多次计算某些情况。您必须删除所有这些重复项。
我认为这不是解决这个问题的好方法。
数学会变得更简单。
假设空插槽是N1,1个插槽car是N2,2个插槽car是N3,3个插槽car是N4。
N1 + N2 +2* N3 +3* N4 =N
我想你可以自己解决剩下的问题。
https://stackoverflow.com/questions/7440262
复制相似问题