Bottom-up 방식으로 직관적으로 구할 수 있는 작은 해들을 구하고 그 작은 해를 이용해서 큰 해를 차례로 구해서 점화식을 도출하였다.
#include <iostream>
using namespace std;
int a[50];
int main() {
//freopen("input.txt", "rt", stdin);
ios_base::sync_with_stdio(false);
int n, i;
cin >> n;
a[1] = 1;
a[2] = 2;
for(i=3; i<=n; i++){
a[i] = a[i-2] + a[i-1];
}
cout << a[n];
return 0;
}
결과는 통과하였다.
사이트의 답안
#include<bits/stdc++.h>
using namespace std;
int dy[50];
int main(){
ios_base::sync_with_stdio(false);
freopen("input.txt", "rt", stdin);
int n;
cin>>n;
dy[1]=1;
dy[2]=2;
for(int i=3; i<=n; i++){
dy[i]=dy[i-1]+dy[i-2];
}
cout<<dy[n];
return 0;
}
사이트의 답과 논리적으로 똑같았다.
또 다른 방법 - Top Down 방식
Top-Down 방식으로도 풀 수 있는데 이 방식은 재귀 + 메모이제이션을 이용한 방식이다. 아래 그림과 같이 재귀식으로 함수를 호출하고 입력 값이 큰 수일수록 반복되는 재귀 함수가 많으므로 시간이 오래걸리기 때문에 메모이제이션 방식으로 한 번 호출한 적이 있으면 그 값을 바로 리턴해서 시간복잡도를 줄일 수 있다.
#include<bits/stdc++.h>
using namespace std;
int dy[50];
int main(){
ios_base::sync_with_stdio(false);
freopen("input.txt", "rt", stdin);
int n;
cin>>n;
dy[1]=1;
dy[2]=2;
for(int i=3; i<=n; i++){
dy[i]=dy[i-1]+dy[i-2];
}
cout<<dy[n];
return 0;
}