Why OJ fails testing my C++ solution?


  • 0
    S

    Ok, my code is not the cleanest one, but why OJ fails testing it, for some specific values like n = 6?
    Xcode does not fail. I am not using global variables, as you can see.

    class Solution {
    public:
    
        int numSquares(int n) {
            vector<int> perfectSquares;
            vector<int> myCache(n, 0);
            for(int i = 1; i <= sqrt(n); ++i){
                perfectSquares.push_back(i * i);
                myCache[i * i] = 1;
            }
            return numSquares_helper(n, perfectSquares, myCache);
        }
        
        int numSquares_helper(int n, vector<int>& perfectSquares, vector<int>& myCache){
            if (n < 1) return 0;
            if (n == 1) return 1;
            if (myCache[n]) return myCache[n];
            int minNum = n;
            int i = 0;
            while(i < perfectSquares.size() && n >= perfectSquares[i]){
                minNum = min(minNum, 1 + numSquares_helper(n - perfectSquares[i], perfectSquares, myCache));
                ++i;
            }
            myCache[n] = minNum;
            return minNum;
        }
        
    };
    

Log in to reply
 

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