栈与递归

#include <iostream>
#include <stack>
#include <string>
#include <vector>


int
fibonacci_recursion(int a)
{// 斐波那契 递归实现
	if (a <= 2) {
		return 1;
	}
	return fibonacci_recursion(a - 1) + fibonacci_recursion(a - 2);
}


int
fibonacci_stack(int n)
{// 斐波那契 栈实现
	std::stack<int> stk;
	int topElement, currentElement = 1;
	if (n <= 2) {
		return 1;
	}
	stk.push(1);
	stk.push(1);
	for (int i = 2; i < n; i++) {
		topElement = stk.top(); stk.pop();
		int temp = stk.top(); stk.pop();
		currentElement = topElement + temp;
		stk.push(topElement);
		stk.push(currentElement);
	}
	return stk.top();
}


void 
print_recursion(const std::string & str)
{
	if (str.size() == 0) {
		return;
	}
	std::cout << str << std::endl;
	print_recursion(std::string(str.c_str(), str.size() - 1));
}



void
print_stack(const std::string & str)
{
	std::stack<std::string> stk;
	stk.push(str);
	while (true) {		
		std::string temp = stk.top();
		if (temp.size() == 0) {
			break;
		}
		std::cout << temp << std::endl;
		stk.pop();
		stk.push(std::string(temp.c_str(), temp.size() - 1));
	}
}


/* *
 * 根据这两个例子, 可以观查出来, 用栈来解决递归问题.
 * 关键在于, 压栈的元素的顺序和数量, 出栈的元素的数量.
 * 那么, 我们可以先看递归实现, 如果递归方式使用的操作数是一个, 那么压栈与出栈的元素个数将是一个
 * 如果, 递归实现的操作数是两个, 那么压栈与出栈的元素个数就应该是两个.
 * 至于多个元素的顺序问题, 一般是将深度下降一位, 栈顶是新元素.
 * 比如, stack[1, 2] (6), 并且需要三个操作数, 那么3, 出栈就将是 2=>1, 入栈的顺序就将是 1=>2=>6.
 * 并且可以看到, 如果一个递归实需要两个操作数, 那么栈中的元素个数最多也就是两个.
 */


int 
main()
{
	std::cout << fibonacci_recursion(12) << std::endl;
	std::cout << fibonacci_stack(12) << std::endl;
	print_recursion("12345");
	print_stack("12345");
	std::cin.get();
	exit(0);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值