279. Perfect Squares

来源:互联网 发布:腾讯企业邮箱域名续费 编辑:程序博客网 时间:2024/04/29 12:13

Difficulty: Medium

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.

language c:

//所有的完美平方数都可以看做是一个普通数加上一个完美平方数//而x = a+b*b,则x的最少完全平方数的个数就是a的加上1//#include <stdlib.h>//#define MAX int min(int a ,int b) {    return (a>b)?b:a;}int numSquares(int n) {    int* p = (int*)malloc((n+1)*sizeof(int));    int i, j;    //let each of the numbers of the array be max to avoid to be chosen    for (i = 0; i <= n; i++) {        p[i] = n+1;    }    //令所有平方数为1    for (i = 1; i*i <= n; i++) {        p[i*i] = 1;    }    for (i = 0; i <= n; i++) {        for (j = 0; i+j*j <= n; j++) {            p[i+j*j] = min(p[i]+1, p[i+j*j]); // p[i+j*j]可能就是平方数,即为1 ,所以取两者最小        }    }    return p[n];}

成绩

0 0