例1:一列数的规则如下: 1、1、2、3、5、8、13、21、34...... 求第30位数是多少。
/*
* @(#)Recrusion.java
*
* Copyright 2015Vision, Inc. All rights reserved.
*/
package test;
/**
* description
*
* @author zhangkaishun
* @version 1.0,2015-9-2
*/
public class Recrusion {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(Fool(4));
}
public static int Fool(int i) {
if (i <= 0)
return 0;
else if (i > 0 && i <= 2)
return 1;
else
return Fool(i - 1) + Fool(i - 2);
}
}
用递归算法求某一个数的阶乘
/*
* @(#)Recrusion1.java
*
* Copyright 2015Vision, Inc. All rights reserved.
*/
package test;
/**
* 求某一个数的阶乘
*
* @author zhangkaishun
* @version 1.0,2015-9-2
*/
public class Recrusion1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(multiply(5));
}
public static int multiply(int t) {
if (t == 1)
return 1;
else
return t * multiply(t - 1);
}
}
结果为:120
java递归全排列问题
这只是一步
/*
* @(#)Recrusion3.java
*
* Copyright 2015Vision, Inc. All rights reserved.
*/
package test;
/**
* description
*
* @author zhangkaishun
* @version 1.0,2015-9-2
*/
public class Recrusion3 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
permute("abcd");
}
public static void permute(String str) {
char[] strArray = str.toCharArray();
permute(strArray, 0, strArray.length - 1);
}
public static void permute(char[] list, int low, int high) {
int i;
if (low == high) {
String cout = "";
for (i = 0; i <= high; i++) {
cout += list[i];
}
System.out.println(cout);
} else {
for (i = low; i <= high; i++) {
char temp = list[low];
list[low] = list[i];
list[i] = temp;
permute(list, low + 1, high);
temp = list[low];
list[low] = list[i];
list[i] = temp;
}
}
}
}
结果:abcd
abdc
acbd
acdb
adcb
adbc
bacd
badc
bcad
bcda
bdca
bdac
cbad
cbda
cabd
cadb
cdab
cdba
dbca
dbac
dcba
dcab
dacb
dabc