Perfect Squares

Given an integer n, return the least number of perfect square numbers that sum to n.
perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 149, and 16 are perfect squares while 3 and 11 are not.

Example 1:

Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.

Approach

Java

public class PerfectSquares {
    public static void main(String[] args) {
        int n = 12;
        System.out.println(numSquares(n));
    }

    static int numSquares(int n) {
        int dp[] = new int[n + 1];
        dp[0] = 0;
        for (int i = 1; i <= n; i++) {
            dp[i] = Integer.MAX_VALUE;
            for (int j = 1; j * j <= i; j++)
                dp[i] = Math.min(dp[i], dp[i - j * j] + 1);
        }
        return dp[n];
    }
}

C++

#include <bits/stdc++.h>
using namespace std;


int numSquares(int n
{
    int dp[n+1];
    dp[0]=0;
       for(int i=1;i<=n;i++)
       {
           dp[i]=INT_MAX;
           for(int j=1;j*j<=i;j++)
                  dp[i]=min(dp[i],dp[i-j*j]+1);
       }
        return dp[n];
}

int main()
{
    int n=12;
    cout<<numSquares(n);
    return 0;
}


No comments:

Post a Comment