최적화
안되는 경우는 money의 최댓값인 10000을 넘는 것을 리턴할 때 -1을 출력하도록 했다. 
#include <iostream>
#include <algorithm>
#include <cstring>
#include <limits.h>
using namespace std;
int table[10001];
int cache[10001];
bool visited[10001];
int dx[] = { 1,-1,0,0 };
int dy[] = { 0,0,1,-1 };
int n;
int go(int money) {
       //cout << money << endl;
       if (money == 0) {
              return cache[money];
       }
       if (money < 0) {
              return 10001;
       }
       int& ret = cache[money];
       if (ret != -1) {
              return ret;
       }
       cache[money] = INT32_MAX;
       for (int i = 0; i < n; ++i) {
              ret = min(ret, 1 + go(money - table[i]));
       }
       return ret;
}
int main(void) {
       memset(cache, -1, sizeof(cache));
       int money;
       cin >> n >> money;
       for (int i = 0; i < n; ++i) {
              cin >> table[i];
       }
       int ans = go(money);
       cout << (ans>10000 ? -1 : ans+1) << endl;;
       return 0;
}


'알고리즘' 카테고리의 다른 글

[DP] 백준 14916 거스름돈  (0) 2018.04.02
[DP] 백준 9084 동전  (0) 2018.04.02
[DP] 백준 2011 암호코드  (0) 2018.01.02
[그래프] 백준 1987 알파벳  (0) 2017.12.14
[그래프] 백준 5567 결혼식  (0) 2017.12.13

+ Recent posts