java - 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 的输出的第二个副本。如果您理解问题,请提供帮助。
解决方案
//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);
}
}
推荐阅读
- javascript - 使用map循环遍历数组时返回null而不是JSX
- ruby-on-rails - 设计 current_user 不是用户实例
- opengl - textureLodOffset 和 texelFetchOffset 相对于它们的预期偏移量有什么区别?
- javascript - 我的功能没有按照定义进行识别(React)
- javascript - 单击窗口/另一个元素时如何更改所有元素的颜色?
- iis - 如何使用 IIS 压缩所有文件
- javascript - 修改 JS 代码以导入 ES 模块以修复错误:Uncaught SyntaxError: Unexpected token 'export'
- python - 如果我导入它,是否可以以某种方式在一个文件中编写一个 def 函数并在另一个文件中使用它?
- javascript - 在 ReactJS/Firebase 中访问数据/结构数据
- asp.net-core - ASP .Net MVC Core 在模型列表中绑定了错误的值