zoukankan      html  css  js  c++  java
  • 平方和等于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;
    }
  • 相关阅读:
    Expanding Rods(二分)
    Monthly Expense(二分)
    sdut1269 走迷宫(dfs)
    走迷宫(dfs)
    C Looooops(扩展欧几里得+模线性方程)
    41. First Missing Positive
    40. Combination Sum II
    39. Combination Sum
    37. Sudoku Solver
    36. Valid Sudoku
  • 原文地址:https://www.cnblogs.com/xiaodi914/p/5853368.html
Copyright © 2011-2022 走看看