一、原題描述
n
passengers board an airplane with exactly n
seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of passengers will:
- Take their own seat if it is still available,
- Pick other seats randomly when they find their seat occupied
What is the probability that the n-th person can get his own seat?
Example 1:
Input: n = 1
Output: 1.00000
Explanation: The first person can only get the first seat.
Example 2:
Input: n = 2
Output: 0.50000
Explanation: The second person has a probability of 0.5 to get the second seat (when first person gets the first seat)
二、簡要翻譯
n個用戶依次登機就坐。第一個用戶丟失了機票,將會隨機選取一個座位,之后的乘客優先坐自己的座位,如果自己座位被占了則隨機找尋一個座位就坐,求問第n個用戶得到自己座位的概率。
三、解答與分析
1、代碼
public double nthPersonGetsNthSeat(int n) { if (n == 1) { return 1.0; } else { return 0.5; } }
2、分析與證明
- 假設有n個用戶,本問題的答案為 f(n)。
- 如果第一個人隨機到了自己的位置,那么后面的人一定按自己機票座位號入座。
- 如果第一個人隨機到了第n個人的位置,那么第 n 個人得到自己座位的概率為0。
- 如果第一個人隨機到了第2個人的位置,那么第 n 個人得到自己座位的概率為f(n-1)。
- 依次類推可得 f(n) = (1 + f(n-1) + f(n-2) + ... + f(2) + 0) / n ;
- 假設當 1< i <= k 時 f(i) = 1/2 , 容易證明f(k+1) = 1/2; 所以f(n) 在n > 1的時候恆等於 1/2 .
論證過程的代碼實現如下
public double nthPersonGetsNthSeat(int n) { if(n==1) return 1.0; double[] dp = new double[n]; double sum = 0; for (int i = 1; i < n; i++) { dp[i] = (1 + sum) / (i + 1); sum += dp[i]; } return dp[n - 1]; }