Why is my solution so slow?


  • 0
    L

    My solution is showed below. It costs 412 ms. But I think the time complexity is n*sqrt(n), right? I know it would be faster if using static keyword but if submit it, it shows a Runtime Error. However, it passes single test by "Run Code" button. How should I use static keyword in my code? Thank you in advance.

    class Solution {
    public:
        int numSquares(int n) {
            vector<int> dp(n + 1, n + 1);
            int square = 2;
            dp[0] = 0;
            dp[1] = 1;
            for (int i = 2; i <= n; i++) {
                if (i == square * square) {
                    dp[i] = 1;
                    square++;
                }
                else {
                    for (int j = square - 1; j > 0; j--) {
                        dp[i] = min(dp[i], 1 + dp[i - j * j]);
                    }
                }
            }
            return dp[n];
        }
    };
    

  • 0

    @lijunray check my solution below using array instead of vector

    class Solution {
    public:
        int numSquares(int n) 
        {
            static int mins[100000]{0};
            static int i = 1;
            if(mins[n]) return mins[n];
            for(; i <= n; ++i)
            {
                int localMin = i;
                for(int j = sqrt(i); j > 0; --j)
                {
                    localMin = min(localMin, mins[i-j*j]+1);
                }
                mins[i] = localMin;
            }
            return mins[n];
        }
    };
    

  • 0

    But actually this solution is flawed, could not handle big number, perhaps you should try the math solution here as follows.

    class Solution {
    public:
        int numSquares(int n) 
        {
            while(!(n&3)) n /= 4;
            if(n%8 == 7) return 4;
            for(int a = sqrt(n); a > 0; --a)
            {
                int b = sqrt(n-a*a);
                if(a*a+b*b == n) return !b? 1 : 2;
            }
            return 3;
        }
    };
    

  • 0

    @lijunray check this post if don't know the theory.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.