网站建设维护招聘,掘金网站建设,wordpress小工具里页面,互粉的网站是怎么做的递归算法设计的基本思想是#xff1a;对于一个复杂的问题#xff0c;把原问题分解为若干个相对简单类同的子问题#xff0c;继续下去直到子问题简单到可以直接求解#xff0c;也就是说到了递推的出口#xff0c;这样原问题就有递推得解。 关键要抓住的是#xff1a; 对于一个复杂的问题把原问题分解为若干个相对简单类同的子问题继续下去直到子问题简单到可以直接求解也就是说到了递推的出口这样原问题就有递推得解。 关键要抓住的是 1递归出口 2地推逐步向出口逼近 样例: example 求5的阶乘。。 例如以下 Java代码 public class Test { static int multiply(int n){ if(n1||n0) return n; else return n*multiply(n-1); } public static void main(String[] args){ System.out.println(multiply(10)); } } public class Test {
static int multiply(int n){
if(n1||n0)
return n;
else
return n*multiply(n-1);
} public static void main(String[] args){
System.out.println(multiply(10));
}
} 上面的multiply是一个阶乘的样例。事实上递归递归从字面上解释就是在方法本身调用自己的方法或者间接调用看上面的程序拿multiply(5)来说 n5;运行 5*multiply(4); -------------------- 这时候看multiply(4) n4 运行 4*multiply(3); ------------------- 看multiply(3) n3,运行 3*multiply(2); --------------- mulitply(2); n2 运行 2*mulitply(1); 这时候return 1;往上返回 2*1向上返回 3*(2*1)向上返回 4*3*2*1 向上返回 5*4*3*2*1 120 所以程序输出120; 这事简单的递归的样例所以能够看出来递归的关键得有递归出口(本体的If语句)还有递归方法 下面是我在百度知道碰到一个朋友的提问,也是关于递归算法的: ------------------------问题------------------------------ 本人刚学JAVA没有不论什么编程基础各位高手见笑。 Java代码 public class Count { static void count(int n) //递归方法 { if (n5) count(n1); System.out.print( n); } public static void main(String args[]) { count(1); System.out.println(); } } public class Count
{static void count(int n) //递归方法{if (n5) count(n1); System.out.print( n);} public static void main(String args[]){count(1);System.out.println();}
} 请具体解说这段程序是怎么运行的我的理解是先运行main函数里的count(1),然后进入count方法N值为1所以运行IF语句直到count(5),此时退出if 循环打印N5 然后应该没有要运行的东西了但是答案是5 4 3 2 1 请问这是怎么回事谢谢 --------------------回答--------------------------- 先运行count(1)然后进入count方法N值为1所以运行IF语句也就是运行count(2),然后进入count方法N值为2所以运行IF语句也就是运行count(3),然后进入count方法N值为3所以运行IF语句也就是运行count(4),然后进入count方法N值为4所以运行IF语句也就是运行count(5),然后进入count方法N值为5所以不运行IF语句然后运行System.out.print( n); 也就是输出5然后本次參数为5的count方法调用结束了返回到调用它的參数为4的count方法中然后运行System.out.print( n);输出4然后一直这样下去输出321 。这里须要说明的是在运行count(5)的时候count(4)、count(3)、count(2)、count(1)都没有运行完成他们都在等自己方法体中的count(n1)运行完成然后再运行System.out.print( n); 转载于:https://www.cnblogs.com/zfyouxi/p/3872678.html