Escolar Documentos
Profissional Documentos
Cultura Documentos
When confronted with a new problem there are two questions you
should ask:
1. Is this problem like, or a special case of, a problem that I already
know how to solve?
2.Is this a problem of size n in one of its variables that I could solve
if I knew the solution to an instance of the same problem (or instances
of all such problems) of size less than n?
Recursion
When the answer to the second question is yes, you will employ
recursion.
There are three steps in formulating a recursive solution to a problem.
1.
2.
3.
2.
3.
4.
Binary Search
5.
Class TowersOfHanoi
-- header file
//pegs
Class TowersOfHanoi
-- implementation
Class Constructor
public TowersOfHanoi(int n_disks) {
if ( n_disks < 1) {
System.err.println( error must start with 1 or more disks in a
tower;
exit(1);
}
num_disks = n_disks;
source = 1; spare = 2; dest = 3;
moveTower(num_disks, source, dest, spare);
}
Class TowersOfHanoi
-- implementation
moveTower
public void moveTower(int disks, int from_peg, int to_peg, int use_peg) {
if (disks == 1)
moveDisk(disks, from_peg, to_peg);
else {
moveTower(disks 1, from_peg, use_peg, to_peg);
moveDisk(disks, from_peg, to_peg);
moveTower(disks 1, use_peg, to_peg, from_peg);
}
}
Class TowersOfHanoi
-- implementation
moveDisk
public void moveDisk(int num, int from_peg, int to_peg) {
System.out.print( moving disk number + num + from peg) ;
System.out.println(from_peg + to peg + to_peg );
}
public void moveTower(int disks, int from_peg, int to_peg, int use_peg) {
if (disks == 1)
33 3
3
2
1
2
21 2
2
2
1
3
2
moveTower(3,1,3,2);
22
33
3
moveTower(2,1,2,3);
moveTower(2,2,3,1);
moveTower(1,1,3,2);
moveTower(1,2,1,3);
moveTower(1,3,2,1);
1
Stack of act. Recs.
Calls to moveTower
screen
1
3
1
2
1
3
1
2
2
1
2
3
1
3
3
power (b, n)
if n = 0
1/ power(b, |n|)
if n < 0
return 1;
n! =
if n = 0
n * (n 1) !
n >= 0
if (n < 0) {
System.out.println( error factorial function requires
non-negative argument\n;
exit(1);
}
if (n == 0)
return 1;
else
return n * factorial (n 1);
}
while(size > 0)
size--;
fibon (n) =
if n = 0
if n = 1
finbon(n-1) + fibon(n-2)
if n > 1
5
2
fibon(4)
1 1
fibon(3) + fibon(2)
fibon(2)
1
1 1
fibon(1) + fibon(0)
fibon(4)
2
fibon(3)
fibon(3)
11
+
00
fibon(1)
fibon(2)
fibon(2)
11
fibon(1)
fibon(1)
fibon(2) + fibon(1)
fibon(1)
+ fibon(0)
+ fibon((0)
fibon(1)
fibon(1)
1
fibon(5)
3
fibon(0)
0
+
fibon(0)
//
//post conditions:
//
//
//exception:
if ( s == NULL)
return TRUE;
if (s.length == 1)
return TRUE;
int len = s.length;
return boolean (s.charAt(0) == s.charAt([len-1])) &&
isPalindrome(s.substring(1,len-2));
}