平方和等于n

#include <iostream>
#include <cmath>
#include <stack>
using namespace std;

int getresult(int num,stack<int> &st,int &min,int &cursum)
{
    if (num - cursum <= 0) return st.size();
    int last = sqrt((float)(num - cursum));
    st.push(last);
    int tmp = last*last;
    cursum += tmp;

    if (tmp == num || min < st.size())
        return st.size();

    int elem = 0;
    while (!st.empty())
    {

        int res = getresult(num, st, min, cursum);
        if (res < min)
            min = res;
        elem = st.top();
        cursum -= elem*elem;
        st.pop();
        elem--;

        if (elem < 1)
        {
            break;
        }
        st.push(elem);
        cursum += elem*elem;
    }
    return min;
}

int getresult(int num)
{
    stack<int> st;
    int min = num;
    int elem = 0;
    int currsum = 0;

    int res = getresult(num, st, min, currsum);
    if (res < min)
        min = res;
    return min;
}


int main()
{
    cout << getresult(4);
    cout<<endl;
    cout << getresult(6);
    cout<<endl;
    cout << getresult(12);
    cout<<endl;
    cout << getresult(15);
    cout<<endl;
    cout << getresult(13);
    cout<<endl;
    cout << getresult(18);
    cout<<endl;
    return 0;
}

 

posted @ 2016-09-08 15:56  随风9  阅读(178)  评论(0编辑  收藏  举报