Skip to content

Instantly share code, notes, and snippets.

@junjiah
Last active September 9, 2015 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save junjiah/bea675c1cf3ae78c296a to your computer and use it in GitHub Desktop.
Save junjiah/bea675c1cf3ae78c296a to your computer and use it in GitHub Desktop.
solved 'Perfect Squares' on LeetCode https://leetcode.com/problems/perfect-squares/
// Runtime: 200ms. Typical DP.
class Solution {
public:
int numSquares(int n) {
vector<int> perfect_records(n + 1, 0);
for (int i = 1; i <= n; ++i) {
int min_to_perfect = INT_MAX;
for (int j = 1; i - j * j >= 0; ++j) {
if (perfect_records[i - j * j] < min_to_perfect) {
min_to_perfect = perfect_records[i - j * j];
}
}
perfect_records[i] = min_to_perfect + 1;
}
return perfect_records.back();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment