/**
* 递归算法
* @param args
*/
public static void main(String[] args) {
// 1.递归组合所有list
System.out.print("递归组合: ");
List<String> list = Lists.newArrayList();
list.add("黄,绿");
list.add("大,小");
list.add("磨砂,镜面");
List<String> list1 = genFullName(0, list);
for (String s : list1) {
System.out.print(s +" ");
}
System.out.println();
System.out.print("斐波那契数列: ");
// 2.斐波那契 1 1 2 3 5 8 13 ...
// 规律:fn(n-1) + fn(n-2) 当前值为前面两个只和
for (int i = 10; i > 0; i--) {
System.out.print(fbnq(i) + " ");
}
}
/**
*递归组合所有list
*
* @param startLine
* @param list
*/
private static List<String> genFullName(int startLine, List<String> list) {
List<String> res = Lists.newArrayList();
// 最后一行
if (startLine == list.size() - 1) {
res.addAll(Arrays.asList(list.get(startLine).split(",")));
return res;
}
String[] upperName = list.get(startLine).split(",");
List<String> downName = genFullName(startLine + 1, list);
for (String uName : upperName) {
for (String dName : downName) {
res.add(uName + ";" + dName);
}
}
return res;
}
/**
* 斐波那契数列
* @param n
* @return
*/
private static int fbnq(int n) {
// 最后一次递
if (n == 1 || n == 2) {
return 1;
}
// 开始归
return fbnq(n - 1) + fbnq(n - 2);
}
递归算法实战
最新推荐文章于 2024-11-14 21:21:03 发布