原文:
一个人从 x = 0 的位置开始走,如果她只能走 2 步或 3 步,找到恰好到达 x = n 的概率。给出步长 2 的概率,即步长 3 的概率为 1–p 例:
input : n = 5, p = 0.20
output : 0.32
explanation :-
there are two ways to reach 5.
2 3 with probability = 0.2 * 0.8 = 0.16
3 2 with probability = 0.8 * 0.2 = 0.16
so, total probability = 0.32.
这是一个简单的问题。它是这个问题的简单延伸:- 下面是上述方法的实现。
c
// cpp program to find probability to
// reach n with p probability to take
// 2 steps (1-p) to take 3 steps
#include
using namespace std;
// returns probability to reach n
float find_prob(int n, float p)
{
double dp[n 1];
dp[0] = 1;
dp[1] = 0;
dp[2] = p;
dp[3] = 1 - p;
for (int i = 4; i <= n; i)
dp[i] = (p)*dp[i - 2] (1 - p) * dp[i - 3];
return dp[n];
}
// driver code
int main()
{
int n = 5;
float p = 0.2;
cout << find_prob(n, p);
return 0;
}
java 语言(一种计算机语言,尤用于创建网站)
// java program to find probability to
// reach n with p probability to take
// 2 steps (1-p) to take 3 steps
import java.io.*;
class gfg {
// returns probability to reach n
static float find_prob(int n, float p)
{
double dp[] = new double[n 1];
dp[0] = 1;
dp[1] = 0;
dp[2] = p;
dp[3] = 1 - p;
for (int i = 4; i <= n; i)
dp[i] = (p) * dp[i - 2]
(1 - p) * dp[i - 3];
return ((float)(dp[n]));
}
// driver code
public static void main(string args[])
{
int n = 5;
float p = 0.2f;
system.out.printf("%.2f",find_prob(n, p));
}
}
/* this code is contributed by nikita tiwari.*/
python 3
# python 3 program to find
# probability to reach n with
# p probability to take 2
# steps (1-p) to take 3 steps
# returns probability to reach n
def find_prob(n, p) :
dp =[0] * (n 1)
dp[0] = 1
dp[1] = 0
dp[2] = p
dp[3] = 1 - p
for i in range(4, n 1) :
dp[i] = (p) * dp[i - 2] (1 - p) * dp[i - 3]
return dp[n]
# driver code
n = 5
p = 0.2
print(round(find_prob(n, p), 2))
# this code is contributed by nikita tiwari.
c
// c# program to find probability to
// reach n with p probability to take
// 2 steps (1-p) to take 3 steps
using system;
class gfg {
// returns probability to reach n
static float find_prob(int n, float p)
{
double []dp = new double[n 1];
dp[0] = 1;
dp[1] = 0;
dp[2] = p;
dp[3] = 1 - p;
for (int i = 4; i <= n; i)
dp[i] = (p) * dp[i - 2]
(1 - p) * dp[i - 3];
return ((float)(dp[n]));
}
// driver code
public static void main()
{
int n = 5;
float p = 0.2f;
console.writeline(find_prob(n, p));
}
}
/* this code is contributed by vt_m.*/
服务器端编程语言(professional hypertext preprocessor 的缩写)
java 描述语言
输出:
0.32
麻将胡了pg电子网站的版权属于:月萌api www.moonapi.com,转载请注明出处