标签:
1、什么是递归
1)举个生活中的例子:假设有一项很繁重的工作,我们总能把它划分为:总工作量=今天的工作+剩下的工作,只要我们每天都在坚持,一点点继续,那么剩下的工作会越来越少,总有一天,我们可以实现我们的梦想!(程序员的自我安慰~)
2)数学上来看:
例如:n的阶乘 f(n) = n!,n为整数
f(n) = 1 n<= 1 (1)
n*f(n-1) n >1 (2)
2、从全排列看递归
改一个字符数组,输出由这些字符组成的全排列:
#include <iostream> #include <cstdlib> using namespace std; template <class T> void print(T*p,int num) { for(int i = 0;i < num;i++) { cout<<p[i]<<" "; } cout<<endl; } template <class T> void permutations(T *p,int first,int last) { if(first == last) //当first = last,p[first:last]只有一个全排列 print(p,last+1); else{ // p[first:last] 有多于一个排列,递归生成这些排列 for(int i = first;i <= last;i++) { swap(p[i],p[first]); permutations(p,first+1,last); swap(p[i],p[first]); } } } int main() { cout << "please enter the numbers!" << endl; char num; int countNum = 0; char arrayNum[1000]; while(cin >> num && num != ‘0‘) { arrayNum[countNum] = num; countNum++; } cout<<endl; permutations(arrayNum,0,countNum-1); return 0; }
标签:
原文地址:http://www.cnblogs.com/1995hxt/p/5598459.html