数据结构算法(1)--递归转化
数据结构算法(1)--递归转化
总结并记录学习数据结构过程中遇到的问题及算法.
一些常见算法:
Note:
- 基础应用.
- 递归的非递归转化.
阶乘
递归实现:
#include <iostream>
using namespace std;
int F(int n)
{
if (n == 0 || n == 1)
return 1;
else
return n * F(n - 1);
}
int main()
{
int s;
cin >> s;
int result = F(s);
cout << result << endl;
system("pause");
}
非递归实现:
#include <iostream>
#include<stack>
using namespace std;
int main()
{
int s, result = 1;
cin >> s;
stack<int> F;
F.push(s);
while (F.size() != 0)
{
int temp = F.top();
F.pop();
if(temp>1)
{
result *= temp;
F.push(temp - 1);
}
}
cout << result << endl;
system("pause");
}
二阶斐波那函数
题目略.
递归实现:
#include <iostream>
using namespace std;
int F(int n)
{
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return F(n - 1) + F(n - 2);
}
int main()
{
int s;
cin >> s;
int result = F(s);
cout << result << endl;
system("pause");
}
非递归实现:
#include <iostream>
#include<stack>
using namespace std;
int main()
{
int s;
cin >> s;
stack<int> F;
int sum = 0;
F.push(s);
while (F.size() != 0)
{
int temp = F.top();
F.pop();
if (temp > 1)
{
F.push(temp - 1);
F.push(temp - 2);
}
else if (temp == 1)
++sum;
}
cout << sum << endl;
system("pause");
}
二阶斐波那函数
递归实现:
#include <iostream>
#include<stdio.h>
using namespace std;
void move(char a, char b)
{
cout << a << "-->" << b << endl;
}
void hanoit(int n, char a, char b, char c)
{
if (n == 1)
move(a, c);
else
{
hanoit(n - 1, a, c, b);
move(a, c);
hanoit(n - 1, b, a, c);
}
}
int main()
{
int n;
cin >> n;
hanoit(n, 'A', 'B', 'C');
system("pause");
}
非递归实现:
博客 https://blog.csdn.net/yhf_naive/article/details/53384148
#include<iostream>
#include<algorithm>
#include <stack>
#include <cstdio>
#include<cmath>
using namespace std;
int temp1 = -1, temp2 = -1;
char s[4] = { 'q','a','b','c' };//为了解题简便,我是从1开始算的
stack<int> a[4];
int c1 = 0;
int rank1[4];
bool compare(int a1, int b1) { //给栈顶元素排序用
if (a[a1].top() >= a[b1].top())
return true;
if (a[a1].top() < a[b1].top())
return false;
return false;
}
bool move1(int before, int after) { //移动物块
if ((a[after].top() - a[before].top()) % 2 == 0)
return false;
a[after].push(a[before].top());
a[before].pop();
temp1 = before; temp2 = after; //记录上一次移动的物块位置
printf("%c -> %c\n", s[temp1], s[temp2]);//printf比cout要快
c1++;
return true;
}
int main() {
int i, N;
cin >> N;
a[1].push(N + 1); //保证栈不会为空
for (i = 0; i < N; i++)
a[1].push(N - i); //初始化
a[2].push(N + 2);
a[3].push(N + 3);
if (N % 2 == 1) { //N为奇数还是偶数,第一次移物块到哪里是不同的
move1(1, 3);
temp1 = 1;
temp2 = 3;
}
else {
move1(1, 2);
temp1 = 1; temp2 = 2;
}
for (i = 1; i <= 3; i++)//初始化栈排序表
rank1[i] = i;
int tt;
while (c1 < pow(2, N) - 1) {
sort(rank1 + 1, rank1 + 4, compare);//按compare函数排序
if (temp2 == rank1[2]) { //刚移动过的物块不会再被移动
if (tt == temp1) //别问我为什么,找规律找出来的
move1(rank1[3], rank1[2]);
else
move1(rank1[3], rank1[1]);
}
else
move1(rank1[2], rank1[1]);
tt = rank1[2];
}
}