Ways of filling 10 places with number from [1..10] such that digit at ith place has value atmost 1 more than the largest value at 1..to ith place

我是研究僧i 提交于 2020-01-14 03:24:09

问题


for example if we consider the case for 3 places with numbers from [1..3]..we can do it in 5 ways:

1 1 1
1 1 2
1 2 1
1 2 2 
1 2 3

In second place we cant have 3 as the difference between 2nd and 1 first place will be more than 1.

Any place (say i ) can have value atmost 1 more than the LARGEST value at its previous positions (i.e from 1 ..i-1)


回答1:


Let dp[i, j] = how many possibilities of generating i positions such that the max is j, following the restrictions.

We have:

dp[0, 0] = dp[1, 1] = 1
dp[i, j > i] = dp[i > 0, 0] = 0
dp[2, 1] = 1*dp[1, 1] + dp[1, 0] <- add 1 at the end
dp[2, 2] = dp[1, 2] + dp[1, 1] <- add 2 at the end

dp[3, 1] = 1*dp[2, 1] + dp[2, 0] <- add 1 at the end
dp[3, 2] = 2*dp[2, 2] + dp[2, 1]  <- add 2 at the end
dp[3, 3] = 3*dp[2, 3] + dp[2, 2] <- add 1, 2 or 3 at the end
sum = 1 + 2 + 1 + 1 = 5

dp[4, 1] = 1*dp[3, 1] + dp[3, 0]
dp[4, 2] = 2*dp[3, 2] + dp[3, 1]
dp[4, 3] = 3*dp[3, 3] + dp[3, 2]
dp[4, 4] = 4*dp[3, 4] + dp[3, 3] 
sum = 1 + 6 + 1 + 3 + 3 + 1 = 15 

dp[i, j] = j*dp[i - 1, j] + (1)
           dp[i - 1, j - 1] (2)
answer = dp[n, 1] + dp[n, 2] + ... + dp[n, n]

(1): We have the max j for the first i - 1 elements already, so we can put anything on position i as long as this doesn't break the rule. This anything is clearly: 1, ..., j.

(2): We don't have the max j for the first i - 1, so we must make it so, by appending j to all those with a max of j - 1. Note that if the max of 1 ... i - 1 is < j - 1, we cannot make the max of 1 ... i to be j while following the restrictions of the problem, so there is no point considering any dp[i - 1, k < j - 1].

This can be implemented in O(n^2), which should be fast enough for for n up to about 5000 on a decent CPU. The memory used is also O(n^2).



来源:https://stackoverflow.com/questions/9998342/ways-of-filling-10-places-with-number-from-1-10-such-that-digit-at-ith-place

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!