完美平方

给一个正整数 n, 找到若干个完全平方数(比如1, 4, 9, ... )使得他们的和等于 n。你需要让平方数的个数最少。

给出 n = 12, 返回 3 因为 12 = 4 + 4 + 4
给出 n = 13, 返回 2 因为 13 = 4 + 9

dp.

/* ***********************************************
Author        :guanjun
Created Time  :2016/8/31 17:17:39
File Name     :1.cpp
************************************************ */
#include <iostream>
#include <vector>
#include <cmath>
#include <string.h>
using namespace std;
int dp[1010];
int n;
int main()
{
    #ifndef ONLINE_JUDGE
    //freopen("in.txt","r",stdin);
    #endif
    //freopen("out.txt","w",stdout);
    while(cin>>n){
        //dp[i]表示 组成i的最小完全平方数的个数
        //那么 dp[i]=(dp[i],dp[i-j*j]+1)
        //初始化 全是1组成的情况
        for(int i=1;i<=n;i++)dp[i]=i;
        for(int i=1;i<=n;i++){
            for(int j=1;j*j<=i;j++){
                dp[i]=min(dp[i],dp[i-j*j]+1);
            }
        }
        cout<<dp[n]<<endl;
    }
    return 0;
}

上面dp的时间复杂度是 O(n^2)空间复杂度是 O(n)

当n非常大的时候,一定会超时。

其实这题还有其他解法....可以用四方定理。四方定理就是:所有自然数至多只要用四个数的平方和就可以表示。

那么问题可以简化成 判断这个数是不是某个数的平方,或者是不是某两个数的平方和,或者是不是某3个数的平方和。   时将复杂度o(n)   但是跑的飞快....

/* ***********************************************
Author        :guanjun
Created Time  :2016/12/1 13:39:31
File Name     :平方数求和.cpp
************************************************ */
#include <bits/stdc++.h>
#define ull unsigned long long
#define ll long long
#define mod 90001
#define INF 0x3f3f3f3f
#define maxn 10010
#define cle(a) memset(a,0,sizeof(a))
const ull inf = 1LL << 61;
const double eps=1e-5;
using namespace std;
priority_queue<int,vector<int>,greater<int> >pq;
struct Node{
    int x,y;
};
struct cmp{
    bool operator()(Node a,Node b){
        if(a.x==b.x) return a.y> b.y;
        return a.x>b.x;
    }
};

bool cmp(int a,int b){
    return a>b;
}
bool check1(ll n) {
    int a=sqrt(n);
    return a*a==n;
}
bool check2(ll n) {
    for(ll i=1;i*i<=n;i++){
        if(check1(n-i*i))return true;
    }
    return  false;
}
bool check3(ll n) {
    for(ll i=1;i*i<=n;i++){
        if(check2(n-i*i))return true;
    }
    return false;
}
int main()
{
    #ifndef ONLINE_JUDGE
    //freopen("in","r",stdin);
    #endif
    //freopen("out.txt","w",stdout);
    ll n;
    while(cin>>n){
        if(n==-1)break;
        if(check1(n)||n==0){
            cout<<1<<endl;
        }
        else if(check2(n)){
            cout<<2<<endl;
        }
        else if(check3(3)){
            cout<<3<<endl;
        }
        else cout<<4<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/pk28/p/5827338.html