一个人“ A”正在从起始位置X = 0步行,任务是找到可以精确达到X = num的概率,如果他/她可以采取2步或3步。步长2的概率即P,步长3的概率为1-P。
输入值
num = 5, p = 0.2
输出结果
0.32
说明
There can be 2 ways to reach num, i.e, 5 2+3 with probability 0.2 * 0.8 = 0.16 3+2 with probability 0.8 * 0.2 = 0.16 So, total probability will be 0.16 + 0.16 = 0.32
输入值
num = 2, p = 0.1
输出结果
0.1
我们将使用动态编程的方法来解决问题。
在解决方案中,我们将-
声明一个大小为num + 1的概率数组,并将其值指定为:set probab [0] = 1,set probab [1] = 0,Set probab [2] = p,Set probab [3] = 1 – p
将i从0迭代到num,同时增加其值
对于每个i,设置probab [i] =(p)* probab [i-2] +(1-p)* probab [i-3]
返回概率[num]
打印结果。
Start Step 1→ declare function to calculate probability of reaching a point with 2 or 3 steps at a time float probab(int num, float p) Declare double probab[num + 1] `Set probab[0] = 1 Set probab[1] = 0 Set probab[2] = p Set probab[3] = 1 – p Loop For int i = 4 and i <= num and ++i Set probab[i] = (p)*probab[i - 2] + (1 - p) * probab[i - 3] End return probab[num] Step 2→ In main() Declare int num = 2 Declare float p = 0.1 Call probab(num, p) Stop
#include <bits/stdc++.h> using namespace std; //函数计算一次到达2步或3步的点的概率 float probab(int num, float p){ double probab[num + 1]; probab[0] = 1; probab[1] = 0; probab[2] = p; probab[3] = 1 - p; for (int i = 4; i <= num; ++i) probab[i] = (p)*probab[i - 2] + (1 - p) * probab[i - 3]; return probab[num]; } int main(){ int num = 2; float p = 0.1; cout<<"probability is : "<<probab(num, p); return 0; }
输出结果
如果运行上面的代码,它将生成以下输出-
probability is : 0.1