首页 > 解决方案 > Java 递归算法

问题描述

编写一个带有一个名为 n 的正 int 参数的方法。该方法将写入 2^n-1 个整数(其中 ^ 是幂运算)。以下是各种 n 值的输出模式:

n=1: Output is: 1 
n=2: Output is: 1 2 1 
n=3: Output is: 1 2 1 3 1 2 1 
n=4: Output is: 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 

等等。请注意,n 的输出始终包含 n-1 的输出,然后是 n 本身,然后是 n-1 的输出的第二个副本。如果您理解问题,请提供帮助。

标签: javaalgorithm

解决方案


//here is a solution that returns the result as a string
// this makes sense because the pattern on both sides of n are the patterns of  n-1 
public static String recursion(int n)
{ 
    if(n == 1)
    {
        return "1";
    }
    else
    {
        return recursion(n-1) + " " + n + " " + recursion(n-1);
    }
}

推荐阅读