当有2 ^ n个条件时,从递归函数返回的更好方法

时间:2015-10-03 07:04:21

标签: java recursion return

假设我n = 3中有boolean a个变量 - bcJava

这些变量可以有8 (2^n = 2^3)个组合。

这些条件用于确定return函数中的recursive语句,如下所示:

static int recursiveFunc(int x){

    boolean a, b, c;

    a = getBoolVal(x);
    b = getBoolVal(x + 1);
    c = getBoolVal(x + 2);

    if(a == true && b == true && c == true)        //7
        return recursiveFunc(x + 1) + recursiveFunc(x + 2) + recursiveFunc(x + 3);

    else if(a == true && b == true && c == false)  //6
        return recursiveFunc(x + 1) + recursiveFunc(x + 2);

    else if(a == true && b == false && c == true)  //5
        return recursiveFunc(x + 1) + recursiveFunc(x + 3);

    else if(a == true && b == false && c == false) //4
        return recursiveFunc(x + 1);

    else if(a == false && b == true && c == true)  //3
        return recursiveFunc(x + 2) + recursiveFunc(x + 3);

    else if(a == false && b == true && c == false) //2
        return recursiveFunc(x + 2);

    else if(a == false && b == false && c == true) //1
        return recursiveFunc(x + 3);

    else                                           //0
        return 0;

}

static boolean getBoolVal(int x){

    if(some condition with respect to x)
        return true;

    else
        return false;

}

正如您所看到的,随着n值的增加,条件的数量会变得非常长。

但是,可以在n + 2步骤(而不是2^n)中轻松地生成 ,如下所示:

String returnStat = "";

if(a == true)
    returnStat += "recursiveFunc(x + 1) + ";

if(b == true)
    returnStat += "recursiveFunc(x + 2) + ";

if(c == true)
    returnStat += "recursiveFunc(x + 3) + ";

if(returnStat == "")
    returnStat = "0";

else
    returnStat = returnStat.substring(0, returnStat.length() - 3); //removing extra " + "

无论如何,我可以将returnStat作为陈述返回吗?也许,像 -

return stringToCode(returnStat);

如果没有,如何克服这种情况?

1 个答案:

答案 0 :(得分:3)

recursiveFunc返回一个int,所以只需加上整数:

int result = 0;

if (a)
    result += recursiveFunc(x + 1);
if (b)
    result += recursiveFunc(x + 2);
if (c)
    result += recursiveFunc(x + 3);

return result;