LeetCode 1227. Airplane Seat Assignment Probability

一、原题描述

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];
    }

猜你喜欢

转载自www.cnblogs.com/onePunchCoder/p/11699121.html