遞歸就是程序自己調用自己( recursion)
一般來說,遞歸需要有邊界條件、遞歸前進段和遞歸返回段。當邊界條件不滿足時,遞歸前進;當邊界條件滿足時,遞歸返回。
1.趣味問題——年齡。
有5個人坐在一起,問第五個人多少歲?他說比第4個人大2歲。問第4個人歲數,他說比第3個人大2歲。問第三個人,又說比第2人大兩歲。問第2個人,說比第一個人大兩歲。最后問第一個人,他說是10歲。請問第五個人多大?用遞歸算法實現。
可以用循環解釋這道題
static int GetAge(int num) { int age = 10; while (num>1) { age += 2; num -= 1; } return age; }
換成遞歸
static int GetAge(int num) { if (num==1) return 10;
return GetAge(num-1)+2; }
如果換成尾遞歸
static int GetAge(int num,int acc) { if (num == 1) return acc; return GetAge(num-1,acc+2); }
3.應用場景
刪除指定路徑下的文件夾里內容以及子文件夾以及子文件夾內容
static void DeleteFolder(string dir) { foreach (string d in Directory.GetFileSystemEntries(dir)) { //判斷路徑是否存在 if (File.Exists(d)) { FileInfo fi = new FileInfo(d); //去除文件夾的只讀屬性 if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1) fi.Attributes = FileAttributes.Normal; File.Delete(d);//直接刪除其中的文件 } else { DirectoryInfo d1 = new DirectoryInfo(d); if (d1.GetFiles().Length != 0) { DeleteFolder(d1.FullName);////遞歸刪除子文件夾 } Directory.Delete(d); } } }
4.結
一般樹狀結構的都可以使用遞歸查詢,比如 查詢地區,樹狀的菜單等等,遞歸比普通的算法耗內存,謹慎使用。還有一種叫作“尾遞歸”就是把上一個方法的返回值當作參數傳給下一個方法,不用像遞歸再向上返回。