forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
279.c
58 lines (48 loc) · 1.22 KB
/
279.c
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
54
55
56
57
58
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include <assert.h>
#define EPSILON 1e-8
/* a bit slow, 144 ms */
int numSquares(int n) {
if (n <= 0) return 0;
if (n == 1) return 1;
int *squares = (int *)calloc(n, sizeof(int));
int *dp = (int *)calloc(n + 1, sizeof(int));
int k;
int storeIndex = 0;
for (k = 1; k <= n; k++) {
double root = sqrt(k);
if (fabs(root - (int)root) < EPSILON) { /* check if k is perfect square */
squares[storeIndex++] = k;
}
}
int i, j;
dp[0] = 0; /* dummy */
dp[1] = 1;
for (i = 2; i <= n; i++) {
int min = INT32_MAX;
for (j = 0; squares[j] <= i && j < storeIndex; j++) {
if (dp[i - squares[j]] + 1 < min) {
min = dp[i - squares[j]] + 1;
}
}
dp[i] = min;
}
int ans = dp[n];
free(squares);
free(dp);
return ans;
}
int main() {
assert(numSquares(1) == 1);
assert(numSquares(2) == 2);
assert(numSquares(3) == 3);
assert(numSquares(4) == 1);
assert(numSquares(5) == 2);
assert(numSquares(12) == 3);
assert(numSquares(13) == 2);
printf("all tests passed!\n");
return 0;
}