題目連結

Coin change!

AC Code

 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// clang-format -style=LLVM -i *.cpp && astyle --style=linux *.cpp && rm *.orig
// && g++ -Wall -Wextra -std=c++11 ...

#ifdef LOCAL
#include <bits/stdc++.h>
using namespace std;

// tree node stuff here...

#endif

static int __initialSetup = []()
{
    // toggle off cout & cin, instead, use printf & scanf
    std::ios::sync_with_stdio(false);
    // untie cin & cout
    cin.tie(NULL);
    return 0;
}
();

class Solution
{
public:
    int numSquares(int n)
    {
        const int N = n + 1;

        vector<int> square;
        for (int i = 1; i * i < N; i++)
            square.push_back(i * i);

        int *dp = new int[N];
        fill(dp, dp + N, INT_MAX);
        dp[0] = 0;
        for (auto i : square) {
            dp[i] = 1;
            for (int j = 0; i + j < N; j++) {
                dp[i + j] = min(dp[j] + 1, dp[i + j]);
            }
        }

        return dp[n];
    }
};

#ifdef LOCAL
int main()
{
    return 0;
}
#endif