算法-第四版-练习1.1.16解答

问题

给出exR1(6)的返回值:

public static String exR1(int n)
{
    if (n <= 0) return "";
    return exR1(n-3) + n + exR1(n-2) + n;
}

解决思路

先手算一下,然后再使用代码验证。
要计算exR1(6),
exR1(6) = exR1(3) + 6 + exR1(4) + 6
exR1(4) = exR1(1) + 4 + exR1(2) + 4 = "114224"
exR1(3) = exR1(0) + 3 + exR1(1) + 3 = "3113”
exR1(2) = exR1(-1) + 2 + exR1(0) + 2 = "22"
exR1(1) = exR1(-2) + 1 + exR1(-1) + 1 = "11"
n < 1时,exR1(n) = ""
exR1(6) = "311361142246"

代码

package com.furzoom.lab.algs.ch101;

public class E10116
{
    public static String exR1(int n)
    {
        if (n <= 0) return "";
        return exR1(n-3) + n + exR1(n-2) + n;
    }

    public static void main(String[] args) {
        System.out.println(exR1(6));
    }

}

结果

311361142246
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页