C# return right solution in VS test, but OJ judged wrong.


  • 0
    W

    The following is my code. For n = 6, VS returns 3, but OJ returns 1.

    public int NumSquares(int n) {

        if (n <= 3) return n;
        int[] dp = new int[n+1];
        int i;
        for (i = 0; i <= 3; ++i) dp[i] = i;
        for (i = 4; i <= n; ++i) {
            dp[i] = dp[i-1] +1;
            for (int j = (int) Math.Sqrt(i); j*j*dp[i] > i; --j) {
                if (i % j*j == 0) {
                    dp[i] = i/ (j*j);
                }
                else {
                    dp[i] = Math.Min(dp[i], dp[i-j*j] + 1);
                }
            }
        }
        return dp[n];
    }

  • 0

    i % j*j should be i % (j*j)


  • 0
    W

    Thanks Stefan,
    It worked. Ha, VS did not follow the precedence as strict as OJ.


Log in to reply
 

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