1、三角数字
packagecom.six;
publicclass TriangleApp {
public static void main(String[] args){
int n = 10;
System.out.println(TriangleApp.trianglewhile(n));
System.out.println(TriangleApp.triagleDigui(n));
}
public static int trianglewhile(int n){
int result = 0;
while(n>0){
result += n;
n--; }
return result;
}
public static int triagleDigui(int n ){
System.out.println("entering"+n);
int res = 0;
if(n==1){
res = 1;
System.out.println("return:"+res);
}else{
res =n+triagleDigui(n-1);
System.out.println("return:"+res); }
return res;
}
}
结果:55
entering10
entering9
entering8
entering7
entering6
entering5
entering4
entering3
entering2
entering1
return:1
return:3
return:6
return:10
return:15
return:21
return:28
return:36
return:45
return:55
55
2、阶乘
public class JIchengApp {
publicstatic void main(String[] args) {
int n = 5;
System.out.println(JIchengApp.Digui(n));
System.out.println(JIchengApp.Xunhuan(n));
System.out.println(JIchengApp.Xunhuan2(n));
}
publicstatic int Digui(int n){
System.out.println("entering"+n);
intres = 1;
if(n==0){
res= 1;
System.out.println("return:"+res);
}else{
res= n*Digui(n-1);
System.out.println("return:"+res); }
returnres;
}
publicstatic int Xunhuan(int n){
intres = 1;
if(n==0) res = 1;
else{
for(inti=1;i<=n;i++){
res*= i; } }
returnres; }
publicstatic int Xunhuan2(int n){
intres = 1;
if(n==0) res = 1;
else{
while(n>0){
res*= n;
n--; }
}
returnres;
}
}
结果:entering5
entering4
entering3
entering2
entering1
entering0
return:1
return:1
return:2
return:6
return:24
return:120
120
120
120
3、全排列英文单词:递归(不包括含有相同字母的单词)
public class WordQuanPailie {
staticint size;
staticint count;
staticchar[] arr = {'l','o','v','e'};
publicstatic void main(String[] args) {
size = arr.length;
WordQuanPailie.pailie(size);
}
//排列
publicstatic void pailie(int newsize){
if(newsize==1){
return; }
//对于大于一个字母的单词,进行排列
for(inti=0;i<newsize;i++){
pailie(newsize-1);//递归调用排序本来长度减一的单词
//知道长度为2,调用遍历方法
if(newsize==2)
display();
//轮换
rotate(newsize);
}
}
//轮换:将第二个字母知道最后一个字母全部左移一位,再讲原本的第一位挪到最右边
publicstatic void rotate(int newsize){
inti = 0;
//获得首位的下标
intposition = size - newsize;
chartemp = arr[position];
//其余全部左移
for(i=position;i<size-1;i++){
arr[i]=arr[i+1];
}
//将最右边的赋值为原首位
arr[i]= temp;
}
//遍历:带着第几个的标志,每行输出6个单词
publicstatic void display(){
//如果是10-99个,则前边一个空格
if(count < 99)
System.out.print("");
//如果是1-9,则前边2个空格,为了对齐
if(count < 9)
System.out.print("");
System.out.print(++count+"");
//输出单词
for(inti=0;i<size;i++){
System.out.print(arr[i]);
}
System.out.print(" ");
if(count%6==0)
System.out.println();
}
}结果是:
1love 2 loev 3 lveo 4 lvoe 5 leov 6 levo
7ovel 8 ovle 9 oelv 10 oevl 11 olve 12 olev
13velo 14 veol 15 vloe 16 vleo 17 voel 18 vole
19elov 20 elvo 21 eovl 22 eolv 23 evlo 24 evol
对于三角数字、阶乘、单词字母全排列以及二分查找,他们的递归的方法都只包含一次对自身的调用,对于汉诺塔和归并排序问题,他们归并的方法包括两次递归调用。
4、汉诺塔:包含三个塔座,和任意数量的盘子。递归实现:把除了最低端盘子外所有盘子形成的子树移动到一个中介塔座上,然后把最低端盘子移动到目标塔座上,最终把子树移动到目标塔座上。
packagecom.six;
publicclass Tower {
static int len = 3;
public static void main(String[] args){
doTower(len,'A','B','C');
}
public static void doTower(int len,char from, char mid, char to){
System.out.println("开始"+len);
if(len==1){
System.out.println(len+"盘子从"+from+"移动到"+to);
}else{
//移动少一层的树从原塔座到中介塔座
doTower(len-1,from,to,mid);
//在从中介塔座移动到目的塔座
doTower(len-1,mid,from,to);
System.out.println(len+"盘子从"+from+"移动到"+to);
}
}
}
5、归并两个有序数组:即创建第三个数组,这个数组按顺序存储从这两个有序数组中取到的所有数据项。
packagecom.six;
publicclass MergeUnrelated {
public static void main(String[] args){
int[] a1 = {23,47,81,95};
int size1 = a1.length;
int[] a2 = {7,14,39,55,62,74};
int size2 = a2.length;
int size3 = size1+size2;
int[] a3 = new int[size3];
merge(a1,size1,a2,size2,a3);
display(a1);
display(a2);
display(a3);
}
public static void merge(int[] a1,intsize1,
int a2[],intsize2,int[] a3){
int i1 = 0;
int i2 = 0;
int i3 = 0;
while(i1<size1 && i2<size2){
if(a1[i1]<a2[i2]){
a3[i3++] = a1[i1++];
}else{
a3[i3++] = a2[i2++];
}
}
while(i1<size1){
a3[i3++] = a1[i1++];
}
while(i2<size2){
a3[i3++] = a2[i2++];
}}
public static void display(int[] a){
for(inti=0;i<a.length;i++){
System.out.print(a[i]+"");
}
System.out.println();
}
}
结果是:
23 47 8195
7 14 3955 62 74
7 14 2339 47 55 62 74 81 95
6、归并排序::对一个数组进行合并排序,(递归)
packagecom.six;
publicclass MergeRelated {
public static void main(String[] args){
int max = 100;
Array2 a = new Array2(max);
a.insert(64);
a.insert(52);
a.insert(34);
a.insert(-78);
a.insert(6);
a.insert(18);
a.insert(45);
a.insert(12);
a.insert(77);
a.display();
a.sort();
a.display();
}}
classArray2{
private int[] a;
private int curlen;
public Array2(int max){
a = new int[max];
curlen = 0;
}
public void insert(int value){ a[curlen++] = value; }
public void display(){
for(int i=0;i<curlen;i++){
System.out.print(a[i]+"");
}
System.out.println();
}
//封装归并排序
public void sort(){
int[] a2 = new int[curlen];
mergeSort(a2,0,curlen-1);
}
//归并排序
public void mergeSort(int[] a2,intleft,int right){
if(left==right){
return;
}else{
int mid =(left+right)/2;
mergeSort(a2,left,mid);
mergeSort(a2,mid+1,right);
merge(a2,left,mid+1,right);
}
}
//合并
public void merge(int[] a2,intleft1,int left2,int right2){
int elems = right2-left1+1;
int right1 = left2-1;
int i2 = 0;
int left = left1;
while(left1<=right1&& left2<=right2){//必须是<=或者>=
if(a[left1] <a[left2]){
a2[i2++] =a[left1++];
}else{
a2[i2++] =a[left2++];
}
}
while(left1<=right1){ a2[i2++] =a[left1++]; }
while(left2<=right2){ a2[i2++] =a[left2++]; }
for(i2 =0;i2<elems;i2++){//注意这里的i2 和elems
a[left+i2] = a2[i2]; } }}
结果是:64 52 34 -78 6 1845 12 77
-78 6 1218 34 45 52 64 77
7、乘方:
packagecom.six;
importjava.util.Scanner;
publicclass Power1 {
static int x;
static int y;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("请输出第一个数");
x = sc.nextInt();
System.out.println("请输出第2个数");
y = sc.nextInt();
int res = Power1.cheng(y);//调用时间复杂度为O(N)的递归方法
System.out.println(res);
int res2 = Power1.cheng2(y);//调用时间复杂度为O(logN)的递归
System.out.println(res2);
}
public static int cheng(int y){
if(y==1){
return x;
}else{
return x*cheng(y-1);
}
}
public static int cheng2(int y){
if(y%2==0){//偶次幂
return chengou(y/2);
}else{
returnchengou(y/2)*x;
}
}
public static int chengou(int y){
int x1 = x*x;
if(y==1){
return x1;
}else{
returnx1*chengou(y-1);
}
}
}
结果是:
请输出第一个数
3
请输出第2个数
6
729
729
任何可以用递归完成的操作都可以用一个栈来实现。递归的方法有时效率可能会较低,这时可以用一个简单循环或者是一个基于栈的方法来代替他。
8、三角数字:用基于栈的方法代替递归方法
packagecom.six;
importjava.io.*;
publicclass StackTriangle1 {
static int theNumber;
static int theAnswer;
static StackX theStack;
static int codePart;
static Params theseParams;
//-------------------------------------------------------------
public static void main(String[] args) throws IOException
{
System.out.print("Enter a number: ");
theNumber = getInt();
recTriangle();
System.out.println("Triangle="+theAnswer);
} // end main()
//-------------------------------------------------------------
public static void recTriangle()
{
theStack = new StackX(10000);
codePart = 1;
while( step() == false) // callstep() until it's true
; // nullstatement
}
//-------------------------------------------------------------
public static boolean step()
{
switch(codePart)
{
case 1: // initial call
theseParams = new Params(theNumber,6);
theStack.push(theseParams);
codePart = 2;
break;
case 2: // method entry
theseParams = theStack.peek();
if(theseParams.n == 1) // test
{
theAnswer = 1;
codePart = 5; // exit
}
else
codePart = 3; // recursive call
break;
case 3: // method call
Params newParams = newParams(theseParams.n - 1, 4);
theStack.push(newParams);
codePart = 2; // go enter method
break;
case 4: // calculation
theseParams = theStack.peek();
theAnswer = theAnswer +theseParams.n;
codePart = 5;
break;
case 5: // method exit
theseParams = theStack.peek();
codePart = theseParams.returnAddress;// (4 or 6)
theStack.pop();
break;
case 6: // return point
return true;
} // end switch
return false;
} // end triangle
//-------------------------------------------------------------
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
//-------------------------------------------------------------
public static int getInt() throws IOException
{
String s = getString();
return Integer.parseInt(s);
}
}////////////////////////////////////////////////////////////////
classParams
{
publicint n;
publicint returnAddress;
publicParams(int nn, int ra)
{
n=nn;
returnAddress=ra;
}
}
////////////////////////////////////////////////////////////////
classStackX
{
privateint maxSize; private Params[]stackArray;
privateint top;
publicStackX(int s) // constructor
{
maxSize = s; // set array size
stackArray = new Params[maxSize]; // create array
top = -1; // no items yet
}
publicvoid push(Params p) { stackArray[++top] = p; }
publicParams pop() { return stackArray[top--]; }
publicParams peek() { return stackArray[top]; }
}
结果是:Enter a number:12
Triangle=78
9、三角数字:针对8中的switch,这里用2个短的while循环代替
packagecom.six;
importjava.io.*;
publicclass StackTriangle2 {
static int theNumber;
static int theAnswer;
static StackX2 theStack;
public static void main(String[] args)throws IOException {
System.out.print("Entera number: ");
System.out.flush();
theNumber = getInt();
stackTriangle();
System.out.println("Triangle="+ theAnswer);
}
public static void stackTriangle() {
theStack = new StackX2(10000);// make a stack
theAnswer = 0; // initializeanswer
while (theNumber > 0) //until n is 1,
{
theStack.push(theNumber);// push value
--theNumber; //decrement value
}
while (!theStack.isEmpty())// until stack empty,
{
intnewN = theStack.pop(); // pop value,
theAnswer += newN;// add to answer
}
}
public static String getString() throwsIOException {
InputStreamReader isr = newInputStreamReader(System.in);
BufferedReader br = newBufferedReader(isr);
String s = br.readLine();
return s;
}
public static int getInt() throwsIOException {
String s = getString();
return Integer.parseInt(s);
}
}
classStackX2 {
private int maxSize; // size of stackarray
private int[] stackArray;
private int top; // top of stack
public StackX2(int s) // constructor
{
maxSize = s;
stackArray = newint[maxSize];
top = -1;
}
public void push(int p) { stackArray[++top]= p; }
public int pop(){ return stackArray[top--]; }
public int peek() { returnstackArray[top]; }
public boolean isEmpty() { return(top == -1); }
}结果是:Enter anumber: 12
Triangle=78