티스토리 뷰

Bottom up 방식

#include<bits/stdc++.h>
using namespace std;
int dy[10];
int main() {
	ios_base::sync_with_stdio(false);
	ifstream cin;
	cin.open("input.txt");
	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[7];
	return 0;
}

 

제일 작은 값을 구하고 그 값을 통해 다음값을 얻는 방식이다.

 

Top down 방식

#include<bits/stdc++.h>
using namespace std;
int dy[10];
int DFS(int x){
	if(dy[x]>0) return dy[x];
	if(x==1 || x==2) return x;
	else {
		return dy[x]=DFS(x-1)+DFS(x-2);
	}
}
int main() {
	ios_base::sync_with_stdio(false);
	ifstream cin;
	cin.open("input.txt");
	int n;
	cin >> n;
	cout<<DFS(n);
	return 0;
}

DFS를 통해 제일 큰값부터 접근하는 방법이다.

dy배열에 이미 값이 나온 것들은 저장하면서 진행되기 떄문에 실행시간을 줄일 수 있다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
글 보관함