Ex 1: 1~N的累加过程,数值1~N的累加可以看成是1~N<spanstyle="font-family:宋体">-1的累加加上N。
publicint sum(int num){ int result =0; if (num ==1){ return1; } return result + num + sum(num -1); }
这里的基本情况就是但
num
==
1
的时候。
当然这个可以不用递归来处理,用一个
for
就行了(而且比用递归更直观)。我们必须能判断什么时候使用递归,什么时候不使用递归,所有问题都可以使用迭代(
for
循环)解决问题。不过有些情况下,迭代方式过于复杂,对某些问题,递归可以写出短小而优雅的代码。
publicclass TowersOfHanoi{ privateint totalDisks; // ------------------------------------------------------ // Sets up the puzzle with the specified number of disks // ------------------------------------------------------ public TowersOfHanoi(int disks){ this.totalDisks = disks; } // ---------------------------------------------------------- // Performs the initial call to moveTower to solve the puzzle. // Moves the disks from tower 1 to tower 3 using tower 2 // ---------------------------------------------------------- publicvoid solve(){ moveTower(totalDisks, 1, 3,2); } // ----------------------------------------------------------------- // Moves the specified number of disks from one tower to another by // moving a subtower of n-1 disks out of the way, moving one disk, // then moving the subtower back, Base case of 1 disk. // ----------------------------------------------------------------- privatevoid moveTower(int numDisks, int start, int end, int temp) { if (numDisks ==1){ moveOneDisk(start, end); }else{ moveTower(numDisks-1, start, temp, end); moveOneDisk(start, end); moveTower(numDisks-1, temp, end, start); } } privatevoid moveOneDisk(int start, int end) { System.out.println("Move one disk from "+ start +" to "+ end); } }