Leetcode Perfect Squares

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.

比较典型的dp

class Solution {
public:
    int numSquares(int n) {
        vector<int> dp(n+1, INT_MAX);
        dp[0] = 0;
        for (int i=1; i<=n; i++) {
            int x = sqrt(i);
            for (int j=1; j<=x; j++) {
                dp[i] = min(dp[i], 1 + dp[i - j * j]);
            }
        }
        return dp[n];
    }
};
posted @ 2015-09-10 00:32  卖程序的小歪  阅读(163)  评论(0编辑  收藏  举报