前幾天在博客園看到有人面試時,遇到遞歸算法題,一時手癢就解了一個。順便網上又找來幾個,也實現了。給大家分享一下,開闊一下思路,沒准你明天面試就能用上。
1、編寫一個方法用於驗證指定的字符串是否為反轉字符,返回true和false。請用遞歸算法實現。(反轉字符串樣式為"abcdedcba")
2、一列數的規則如下: 1、1、2、3、5、8、13、21、34...... 求第30個是多少
3、一列數的規則如下: 1、12、123、1234、12345、123456......,求第n個數的遞歸算法(n<=9)。
4、將一整數逆序,如987654321變為123456789。
5、一個射擊運動員打靶,靶一共有10環,連開10槍打中90環的可能行有多少種?
以上的前提:不能用數組 或轉成字符串處理,也不能用內置函數,如C#的冪函數(Math.Pow)
1 using System;
2
3 namespace RecursionAlgorithms
4 {
5 class Program
6 {
7 private static bool fn1(ref string str, ref int from, ref int to)
8 {
9 if (from >= to) return true;
10 if (str[from++] != str[to--]) return false;
11 return fn1(ref str, ref from, ref to);
12 }
13 private static int fn2(int i)
14 {
15 return i <= 2 ? 1 : fn2(i - 2) + fn2(i - 1);
16 }
17 private static long fn3(long x, ref long n)
18 {
19 return (x <= 1) ? x : fn3(x - 1, ref n) + x * (n *= 10);
20 }
21 private static long fn4(long x, ref long n)
22 {
23 return (x < 10) ? x : fn4(x / 10, ref n) + (x % 10) * (n *= 10);
24 }
25 private static long fn5(int n, int sum)
26 {
27 if ((n == 1 && sum <= 10) || (sum == n * 10)) return 1;
28 if (sum > n * 10 || sum < 0) return 0;
29 long ok = 0;
30 for (int i = 0; i <= 10; i++)
31 {
32 ok += fn5(n - 1, sum - i);
33 }
34 return ok;
35 }
36
37 static void Main(string[] args)
38 {
39 string[] strs = { "", "a", "aa", "aba", "abba", "abcba", "ab", "abc", "abca" };
40 for (int i = 0; i < strs.Length; i++)
41 {
42 string str = strs[i];
43 int from = 0, to = str.Length - 1;
44 Console.WriteLine("{0} is {1}", str, fn1(ref str, ref from, ref to));
45 }
46 for (int i = 1; i <= 30; i++) Console.Write("{0}:{1} \t", i, fn2(i));
47 long n = 1, m = 1, t = 0;
48 for (int i = 0; i <= 9; i++, n = m = 1)
49 {
50 Console.Write("\n {0} ==> {1}", t = fn3(i, ref n), fn4(t, ref m));
51 }
52 Console.WriteLine("\n{0}種可能性", fn5(10, 90));
53 }
54 }
55 }
測試一下:

遞歸算法很有意思的,並不是說函數調用自身就一定是遞歸算法。有一次我做面試官,有一童鞋在一道簡單的遞歸函數中,還用到了for循環,當場被我Pass(當然還有其他因素)
總結一下遞歸算法的解題思路:
首先步驟分解,寫出最后一次遞歸(n=1)的計算公式,然后是倒數第二次(n=2),n=3....,最后歸納出遞歸算法
如第二題:fn(1)=1;f(2)=1;f(3)=f(1)+f(2);----> f(n)=f(n-2)+f(1),那么很容易就寫出這個遞歸函數
f(n)={n<=2?1:fn(n-2)+f(n-1)}
本文同時發表在CSDN:http://blog.csdn.net/yzx226/archive/2011/02/20/6195999.aspx

