递归(分治)

分治(divide and conquer):
将原来的问题划分成规模较小结构与原问题相同或相似的子问题,分别解决这些子问题,最后合并子问题的解,得到原问题的解.

1.递归求解n的阶乘

#include <iostream>
using namespace std;
int F(int n) {
    if (n == 0) return 1;
    else return F(n - 1) * n;
}
int main() {
    int n;
    scanf("%d",&n);
    cout<<F(n);
    return 0;
}

1.输入n = 3;调用F(3),
2.n 0, 返回 F (2) * 3;
3.n = 2 0 ,返回 F(1) * 2;
4.n = 1 0, 返回 F(0) * 1;
5,n = 0, F(0) = 1;
6.F(1) = 1;
7.F(2) = F(1) * 2 = 2;
8.F(3) = F(2) * 3 = 6;

2.Fibonacci数列的第n项

数列前几项 1, 1, 2 , 3 , 5, 8 , 13, 21,…..
F(0) = 1, F(1) = 1, F(n) = F(n-1) + F(n-2) (n>=2)

#include <iostream>
using namespace std;
int F(int n) {
    if (n == 0 || n == 1) return 1;
    else return F(n - 1) + F(n - 2);
}
int main() {
    int n;
    scanf("%d",&n);
    cout<<F(n);
    return 0;
}

1,输入n = 3, 返回 F(2) + F(1) ;
2, F(1) = 1; F(2) = F(0) + F(1) = 2;
3. F(3) = 3;

3.全排列(Full Permutation)

全排列指的是n个整数的所有排列,按从小到大的顺序输出n个整数的全排列,其中( a1,a2,....an a 1 , a 2 , . . . . a n )的顺序小于( b1,b2....bn b 1 , b 2 . . . . b n ): a1=b1,a2=b2....an=bn,ai<bi a 1 = b 1 , a 2 = b 2 . . . . a n = b n , a i < b i
举个例子:(1 - 3)的从小到大的顺序全排列:
(1,2,3),(1,3,2)(2,1,3),(2,3,1)(3,1,2),(3,2,1)
从分治的角度考虑,可以划分为多个子问题,"1开头的全排列","2开头的全排列"...
P[ ] 存放当前排列
hashtable[x]:当x在当前的排列P中时,hashtable[x] = true;

#include <iostream>
using namespace std;
const int maxn = 4;
int n, P[maxn], hashTable[maxn] = {false};
void generateP(int index) {
    if (index == n+1) {
        for (int i = 1; i <= n; i++) {
            cout<<P[i];
        }
        cout<<endl;
    }
    for (int x = 1; x <= n; x++) {
        if (hashTable[x] == false) {
            P[index] = x;
            hashTable[x] = true;
            generateP(index + 1);
            hashTable[x] = false;
        }
    }
}

int main() {
    n = 3;
    generateP(1);
    return 0;
}
    原文作者:递归与分治算法
    原文地址: https://blog.csdn.net/u014281392/article/details/80862701
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞