You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
923 B

#include <bits/stdc++.h>
using namespace std;
//递归版本
int ans;
void play_recursion(int n) {
ans += n;
if (n == 1 || n == 2) return;
play_recursion(n - 1);
play_recursion(n - 2);
}
//利用栈的版本
int play_stack(int n) {
//特判
if (n == 1 || n == 2) return n;
//栈
stack<int> s;
//初始化
s.push(1);
s.push(2);
int sum;
for (int i = 3; i <= n; i++) {
int y = s.top();
s.pop();
int x = s.top();
s.pop();
sum = y + x + i;
s.push(y);
s.push(sum);
}
return s.top();
}
int main() {
//递归版本
for (int i = 1; i <= 10; i++) {
ans = 0;
play_recursion(i);
cout << ans << " ";
}
cout << endl;
//栈+循环版本
for (int i = 1; i <= 10; i++)
cout << play_stack(i) << " ";
return 0;
}