蓝桥杯 第一讲

一、递归

就是在运行的过程中调用自己。

构成递归需具备的条件:

1. 子问题须与原始问题为同样的事,且更为简单;

2. 不能无限制地调用本身,须有个出口,化简为非递归状况处理。

例题:

  1. 斐波那契数列—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;
}

3.递归实现指数型枚举

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;
}

  4.递归实现组合型枚举

#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;
}

二、递推

  1.斐波那契数列

#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;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值