首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Eclipse开发 >

将递归改为循环

2013-04-20 
将递归改成循环P(i,j)P(i-1,j-1)*p0+P(i,j-1)*(1-p0)其中p0已知。递归可以做,问各位大神如何改成循环来做

将递归改成循环
P(i,j)=P(i-1,j-1)*p0+P(i,j-1)*(1-p0)
其中p0已知。递归可以做,问各位大神如何改成循环来做呢? 
补充一下,当i=0时候,返回1;当i>j时候返回0
我写的递归是
 
double p(i,j){
    double p0;//这是一个可以求出的数,这里就用常数来表示吧
    if(i==0){
    return 1;
}else if(i>j){
    return o;
}
else{
    return p(i-1,j-1)*p0 + p(i,j-1)*(1-p0);
}
 
}
 现在想换成循环来做,求各位大神帮忙!
[解决办法]

package com.tur.demo;

import java.util.Arrays;

public class Hello {
    /**
     * 递归实现
     * @param i
     * @param j
     * @return
     */
    static double p(int i, int j){
        double p0 = 0.6;//这是一个可以求出的数,这里就用常数来表示吧

        if(i == 0) { return 1; }
        if(i > j)  { return 0; }

        return p(i - 1, j - 1) * p0 + p(i, j - 1) * (1 - p0);
    }

    /**
     * 非递归实现
     * @param i
     * @param j
     * @return
     */
    static double pExt(int i, int j) {
        if(i == 0) { return 1; }
        if(i > j)  { return 0; }

        double p0 = 0.6;
        double[][] result = new double[100][100]; // 这个空间得根据你的数据空间来决定.

        Arrays.fill(result[0], 1);

        // 把二维数组换成两个一维数组,这样会节省很多空间.
        for (int row = 1; row <= i; ++row) {
            for (int col = 1; col <= j; ++col) {
                result[row][col] = result[row - 1][col - 1] * p0 + result[row][col - 1] * (1 - p0);
            }
        }

        for (int row = 0; row <= i; ++row) {
            for (int col = 0; col <= j; ++col) {
                System.out.printf("%5f, ", result[row][col]);
            }


            System.out.println();
        }

        return result[i][j];
    }

    static double pExt2(int i, int j) {
        if(i == 0) { return 1; }
        if(i > j)  { return 0; }

        double p0 = 0.6;
        double[] previous = new double[100];
        double[] current = new double[100];

        Arrays.fill(previous, 1);
        Arrays.fill(current, 1);

        for (int row = 1; row <= i; ++row) {
            for (int col = 0; col <= j; ++col) {
                current[col] =  (row > col) ? 0 : (previous[col - 1] * p0 + current[col - 1] * (1 - p0));
            }

            for (int col = 0; col <= j; ++col) {
                System.out.printf("%5f, ", current[col]);
            }

            System.out.println();

            double[] temp = previous;
            previous = current;
            current = temp;
        }

        return previous[j]; // 最因为最后current指向了i的下一行.
    }

    public static void main(String[] args) {
        System.out.println(p(8, 8));
        System.out.println(pExt(8, 8));
        System.out.println(pExt2(8, 8));
    }
}

热点排行