递归法画*图?
来看看这个算法,
题目要求是:
要求用递归法
第1行1颗*
第2行2颗*
。。。
第n行n颗*
第n+1行n颗*
。。。
第2n行1颗*
我想问问这个怎么想的啊,那个p是起什么作用,有人精通这个吗?
看得我晕死了,谁接受一下吗
public class Test{
static int n = 3;
static int p = 0;
public static void main(String[] args) {
long count = fun(n);
System.out.println();
System.out.println("Count:" + count);
}
private static long fun(int _n){
if(_n==2){
printStar(p+1);
printStar(p+2);
printStar(p+2);
printStar(p+1);
return 6;
}
long count = 0;
if(_n>1){
p++;
printStar(p);
long tmp = fun(_n-1);
count = tmp + 2*_n;
printStar(p);
p--;
}
return count;
}
private static void printStar(int k){
for(int i=0; i<k; i++)
System.out.print('*');
System.out.println();
}
}
另外再出个类似题目,也是用递归法,画出下面的图:
*
**
*
****
*
**
*
********
*
**
*
****
*
**
*
题目要求是:
要求用递归法
第1行1颗*
第2行2颗*
。。。
第n行n颗*
第n+1行n颗*
。。。
第2n行1颗*
我想问问这个怎么想的啊,那个p是起什么作用,有人精通这个吗?
看得我晕死了,谁接受一下吗
public class Test{
static int n = 3;
static int p = 0;
public static void main(String[] args) {
long count = fun(n);
System.out.println();
System.out.println("Count:" + count);
}
private static long fun(int _n){
if(_n==2){
printStar(p+1);
printStar(p+2);
printStar(p+2);
printStar(p+1);
return 6;
}
long count = 0;
if(_n>1){
p++;
printStar(p);
long tmp = fun(_n-1);
count = tmp + 2*_n;
printStar(p);
p--;
}
return count;
}
private static void printStar(int k){
for(int i=0; i<k; i++)
System.out.print('*');
System.out.println();
}
}
另外再出个类似题目,也是用递归法,画出下面的图:
*
**
*
****
*
**
*
********
*
**
*
****
*
**
*
...全文
相关推荐
C#递归算法画树C#递归算法画树C#递归算法画树
/ 递归处理左子树 DrawTree(value * 2, level - 1); // 递归处理右子树 DrawTree(value * 2 + 1, level - 1);}// 调用开始节点DrawTree
递归法求N的阶乘
在编程领域,递归是一种强大的算法,它通过函数或子程序自身调用来解决问题。本示例聚焦于使用C语言实现递归法来计算一个整数N的阶乘(Factorial)。
图的深度优先遍历和广度优先遍历算法
图的广度优先遍历算法图的广度优先遍历(Breadth-First Search,BFS)也是一个常用的图遍历算法。
void reverse(char *source)实现字符串逆序,递归法
从键盘输入字符串,用函数void reverse(char *source)通过递归法实现字符串逆序.
递归法应用-角谷定理.rar
通过这些扩展,你不仅可以深入理解递归法,还能体验到实际编程项目中的问题解决和优化过程。在实践中学习和应用理论知识,这对于计算机科学的学习至关重要。


