程序调用自身的编程技巧称为递归( recursion)。递归做为一种算法在程序设计语言中广泛应用。递归有直接递归和间接递归
(1)必须有可最终达到的终止条件,否则程序将陷入无穷循环;
(2)子问题在规模上比原问题小,或更接近终止条件;
(3)子问题可通过再次递归调用求解或因满足终止条件而直接求解;
(4)子问题的解应能组合为整个问题的解。
static StringBuffer str = new StringBuffer(); /** * //汉诺塔问题 * @param n 盘子的个数 * @param x 将要移动盘子柱子 * @param y 要借用的柱子 * @param z 要移动到的柱子 * @return */ public static String hanio(int n, Object x, Object y, Object z) { //String str =""; if(1 == n) str.append(move(x, n, z) + "\n"); else { hanio(n-1, x, z, y); str.append(move(x, n, z) + "\n") ; hanio(n-1, y, x, z); } return str.toString(); } private static String move(Object x, int n, Object y) { //System.out.println("Move " + n + " from " + x + " to " + y); return "Move " + n + " from " + x + " to " + y; }
/** * fibonacci数列 * @param n * @return */ public static long fibonacci(int n) { if((0 == n) || (1 == n)) { return n; }else { return fibonacci(n-1) + fibonacci(n-2); } }
/** * 累加,从1加到n,即1+2+3+4+...+n * @param n 要累加到的数值 * @return 累加的结果 */ public static long total(int n) { if(1 == n) { return n; }else { return total(n-1) + n; } }
/** * 从1到n的累积,即1*2*3*...*n * @param n 要累乖到的数值 * @return */ public static long accumulate(int n) { if(1 == n) { return n; }else { return accumulate(n-1) * n; } }
/** * 用递归算法求数组中的最大值 * @param a 数组 * @param low 数组下标 * @param heigh 数组上标 * @return */ public static int Max(int[] a, int low, int heigh) { int max; if(low > heigh-2) { if(a[low] > a[heigh]) max = a[low]; else max = a[heigh]; }else { int mid = (low + heigh)/2; int max1 = Max(a, low, mid); int max2 = Max(a, mid+1, heigh); max = max1>max2 ? max1 : max2; } return max; }
/** * 用递归算法求解数字塔问题 * @param n 数字塔的行数 * @return 数字塔的字符串 */ public static String tourData(int n) { String str = new String(); if(1 == n) { str = rowData(n) + "\n"; return str; } else { str = tourData(n-1) + rowData(n) + "\n"; } return str; } private static String rowData(int n) { String str = new String(); for(int i=0; i<n; i++) { str = str+ n + " "; } return str; }