一、递归
就是在运行的过程中调用自己。
构成递归需具备的条件:
1. 子问题须与原始问题为同样的事,且更为简单;
2. 不能无限制地调用本身,须有个出口,化简为非递归状况处理。
例题:
- 斐波那契数列—fibonacci
#include<iostream>
using namespace std;
int f(int n)
{
if (n == 1 || n == 2) return 1;
return f(n - 1) + f(n - 2);
}
int main()
{
int n;
cin >> n;
cout << f(n) << endl;
//system("pause");
return 0;
}
2.全排列
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
const int N = 15;
int n;
int a[N];
bool used[N];//表示这个数是否被使用过
void dfs(int u)
{
if (u > n)//边界
{
for (int i = 1; i <= n; i++)
{
cout << a[i] << " ";
}
cout << endl;
return;
}
//每个位置可以放的数字
for (int i = 1; i <= n; i++)
{
if (!used[i])//该数字没有被使用过,则可以放在该位置
{
a[u] = i;
used[i] = true;
dfs(u + 1);
used[i] = false;
}
}
}
int main()
{
cin >> n;
dfs(1);
system("pause");
return 0;
}
1.每个数都有两种情况 选 或者 不选
2.结果可以为空集
#include<iostream>
#include<cstring>
#include<sstream>
#include<algorithm>
using namespace std;
const int N = 16;
int n;
int a[N];//记录每个数的转态 0 未访问 1 选中 2 未选中
void dfs(int u)
{
if (u > n)
{
for (int i = 1; i <= n; i++)
if (a[i] == 1) printf("%d ", i);
printf("\n");
return;
}
//不选这个数
dfs(u + 1);
//选择这个数
a[u] = 1;
dfs(u + 1);
}
int main()
{
cin >> n;
dfs(1);
system("pause");
return 0;
}
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 30;
int n, m;
int a[N];
bool used[N];
void dfs(int u)
{
if (u > m)//边界
{
for (int i = 1; i <= m; i++)
cout << a[i] << " ";
cout << endl;
return;
}
for (int i = 1; i <= n; i++)
{
if (!used[i] && i > a[u - 1])//这个数没被用过,则可以放在该位置
{
used[i] = true;
a[u] = i;
dfs(u + 1);
used[i] = false;
}
}
}
int main()
{
cin >> n >> m;
dfs(1);
return 0;
}
二、递推
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 50;
int a[N];
int n;
int main()
{
cin >> n;
a[1] = 0;
a[2] = 1;
for (int i = 3; i <= n; i++) a[i] = a[i - 1] + a[i - 2];
for (int i = 1; i <= n; i++) cout << a[i] << " ";
return 0;
}
动态规划的写法
#include<iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int a = 0, b = 1;
if(n == 1) cout << a << endl;
else
{
cout << a << " " << b << " ";
for(int i = 3; i <= n; i++ )
{
if(i % 2 != 0)
{
a += b;
cout << a << " ";
}
else
{
b += a;
cout << b << " ";
}
}
}
return 0;
}