📜  计算将数字表示为完全平方和的方法

📅  最后修改于: 2022-05-13 01:56:04.902000             🧑  作者: Mango

计算将数字表示为完全平方和的方法

给定一个整数N ,任务是找到将数字N表示为完全平方和的方法的数量。

例子:

朴素方法:想法是将所有小于或等于N的完美平方存储在一个数组中。现在问题归结为使用允许重复的数组元素找到求和到N的方法,这可以使用递归来解决。请按照以下步骤解决问题:

  • 将所有小于或等于N的完美平方存储在数组psquare[]中。
  • 创建一个递归函数countWays(index, target)接受两个参数index ,(最初是 N-1) 目标(最初是 N):
    • 处理基本情况:
      • 如果 目标为 0,返回 1。
      • 如果indextarget小于 0,则返回 0。
    • 否则,通过从目标中减去元素 psquare[index] 并递归调用目标的剩余值,将元素psquare[index]包含在总和中。
    • 通过移动到下一个索引并递归调用相同的目标值,从总和中排除元素psquare[index]
    • 返回包含和排除元素得到的总和。
  • 打印countWays(N-1, N)的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Store perfect squares
// less than or equal to N
vector psquare;
 
// Utility function to calculate perfect
// squares less than or equal to N
void calcPsquare(int N)
{
    for (int i = 1; i * i <= N; i++)
        psquare.push_back(i * i);
}
 
// Function to find the number
// of ways to represent a number
// as sum of perfect squares
int countWays(int index, int target)
{
    // Handle the base cases
    if (target == 0)
        return 1;
 
    if (index < 0 || target < 0)
        return 0;
 
    // Include the i-th index element
    int inc = countWays(
        index, target - psquare[index]);
 
    // Exclude the i-th index element
    int exc = countWays(index - 1, target);
 
    // Return the result
    return inc + exc;
}
 
// Driver Code
int main()
{
    // Given Input
    int N = 9;
 
    // Precalculate perfect
    // squares <= N
    calcPsquare(N);
 
    // Function Call
    cout << countWays(psquare.size() - 1, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
public class GFG {
 
    // Store perfect squares
    // less than or equal to N
    static ArrayList psquare = new ArrayList<>();
 
    // Utility function to calculate perfect
    // squares less than or equal to N
    static void calcPsquare(int N)
    {
        for (int i = 1; i * i <= N; i++)
            psquare.add(i * i);
    }
 
    // Function to find the number
    // of ways to represent a number
    // as sum of perfect squares
    static int countWays(int index, int target)
    {
        // Handle the base cases
        if (target == 0)
            return 1;
 
        if (index < 0 || target < 0)
            return 0;
 
        // Include the i-th index element
        int inc
            = countWays(index, target - psquare.get(index));
 
        // Exclude the i-th index element
        int exc = countWays(index - 1, target);
 
        // Return the result
        return inc + exc;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given Input
        int N = 9;
 
        // Precalculate perfect
        // squares <= N
        calcPsquare(N);
 
        // Function Call
        System.out.print(countWays(psquare.size() - 1, N));
    }
}
 
// This code is contributed by Kingash.


Python3
# Python3 program for the above approach
 
# Store perfect squares
# less than or equal to N
psquare = []
 
# Utility function to calculate perfect
# squares less than or equal to N
def calcPsquare(N):
     
    for i in range(1, N):
        if i * i > N:
            break
         
        psquare.append(i * i)
 
# Function to find the number
# of ways to represent a number
# as sum of perfect squares
def countWays(index, target):
     
    # Handle the base cases
    if (target == 0):
        return 1
 
    if (index < 0 or target < 0):
        return 0
 
    # Include the i-th index element
    inc = countWays(index, target - psquare[index])
 
    # Exclude the i-th index element
    exc = countWays(index - 1, target)
 
    # Return the result
    return inc + exc
 
# Driver Code
if __name__ == '__main__':
     
    # Given Input
    N = 9
 
    # Precalculate perfect
    # squares <= N
    calcPsquare(N)
 
    # Function Call
    print (countWays(len(psquare) - 1, N))
 
# This code is contributed by mohit kumar 29


C#
using System.IO;
using System;
using System.Collections;
 
class GFG {
    // Store perfect squares
    // less than or equal to N
    static ArrayList psquare = new ArrayList();
 
    // Utility function to calculate perfect
    // squares less than or equal to N
    static void calcPsquare(int N)
    {
        for (int i = 1; i * i <= N; i++)
            psquare.Add(i * i);
    }
 
    // Function to find the number
    // of ways to represent a number
    // as sum of perfect squares
    static int countWays(int index, int target)
    {
        // Handle the base cases
        if (target == 0)
            return 1;
 
        if (index < 0 || target < 0)
            return 0;
 
        // Include the i-th index element
        int inc = countWays(index,
                            target - (int)psquare[index]);
 
        // Exclude the i-th index element
        int exc = countWays(index - 1, target);
 
        // Return the result
        return inc + exc;
    }
 
    static void Main()
    {
       
        // Given Input
        int N = 9;
 
        // Precalculate perfect
        // squares <= N
        calcPsquare(N);
 
        // Function Call
        Console.WriteLine(countWays(psquare.Count - 1, N));
    }
}
 
// This code is contributed by abhinavjain194.


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Store perfect squares
// less than or equal to N
vector psquare;
 
// Utility function to calculate
// perfect squares <= N
void calcPsquare(int N)
{
    for (int i = 1; i * i <= N; i++)
        psquare.push_back(i * i);
}
 
// DP array for memoization
vector > dp;
 
// Recursive function to count
// number of ways to represent
// a number as a sum of perfect squares
int countWaysUtil(int index, int target)
{
    // Handle base cases
    if (target == 0)
        return 1;
    if (index < 0 || target < 0)
        return 0;
 
    // If already computed, return the result
    if (dp[index][target] != -1)
        return dp[index][target];
 
    // Else, compute the result
    return dp[index][target]
           = countWaysUtil(
                 index, target - psquare[index])
 
             + countWaysUtil(
                   index - 1, target);
}
 
// Function to find the number of ways to
// represent a number as a sum of perfect squares
int countWays(int N)
{
    // Precalculate perfect squares less
    // than or equal to N
    calcPsquare(N);
 
    // Create dp array to memoize
    dp.resize(psquare.size() + 1,
              vector(N + 1, -1));
 
    // Function call to fill dp array
    return countWaysUtil(psquare.size() - 1, N);
}
 
// Driver Code
int main()
{
    // Given Input
    int N = 9;
 
    // Function Call
    cout << countWays(N);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
public class GFG {
     
    // Store perfect squares
    // less than or equal to N
    private static ArrayList psquare;
 
     
    // Utility function to calculate
    // perfect squares <= N
    private static void calcPsquare(int n) {
 
        for (int i = 1; i * i <= n; i++)
            psquare.add(i * i);
         
    }
     
    // DP array for memoization
    private static int[][] dp;
     
    // Recursive function to count
    // number of ways to represent
    // a number as a sum of perfect squares
    private static int countWaysUtil(int index, int target) {
        // Handle base cases
        if (target == 0)
            return 1;
        if (index < 0 || target < 0)
            return 0;
      
        // If already computed, return the result
        if (dp[index][target] != -1)
            return dp[index][target];
      
        // Else, compute the result
        return dp[index][target]
               = countWaysUtil(
                     index, target - psquare.get(index))
      
                 + countWaysUtil(
                       index - 1, target);
    }
     
    // Function to find the number of ways to
    // represent a number as a sum of perfect squares
    private static int countWays(int n) {
        // Precalculate perfect squares less
        // than or equal to N
        psquare = new ArrayList();
        calcPsquare(n);
      
        // Create dp array to memoize
        dp = new int[psquare.size()+1][n+1];
        for(int i = 0; i<=psquare.size(); i++)Arrays.fill(dp[i], -1);
      
        // Function call to fill dp array
        return countWaysUtil(psquare.size() - 1, n);
    }
 
 
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given Input
        int N = 9;
 
        // Function Call
        System.out.print(countWays(N));
    }
     
}
 
// This code is contributed by Dheeraj Bhagchandani.


Python3
# Python3 program for the above approach
from math import sqrt
 
# Store perfect squares
# less than or equal to N
psquare = []
 
# DP array for memoization
dp = []
 
# Utility function to calculate
# perfect squares <= N
def calcPsquare(N):
     
    global psquare
    for i in range(1, int(sqrt(N)) + 1, 1):
        psquare.append(i * i)
 
# Recursive function to count
# number of ways to represent
# a number as a sum of perfect squares
def countWaysUtil(index, target):
     
    global dp
     
    # Handle base cases
    if (target == 0):
        return 1
    if (index < 0 or target < 0):
        return 0
 
    # If already computed, return the result
    if (dp[index][target] != -1):
        return dp[index][target]
 
    dp[index][target] = (countWaysUtil(
                               index, target - psquare[index]) +
                         countWaysUtil(index - 1, target))
 
    # Else, compute the result
    return dp[index][target]
 
# Function to find the number of ways to
# represent a number as a sum of perfect squares
def countWays(N):
     
    global dp
    global psquare
     
    # Precalculate perfect squares less
    # than or equal to N
    calcPsquare(N)
    temp = [-1 for i in range(N + 1)]
     
    # Create dp array to memoize
    dp = [temp for i in range(len(psquare) + 1)]
 
    # Function call to fill dp array
    return countWaysUtil(len(psquare) - 1, N) - 1
 
# Driver Code
if __name__ == '__main__':
     
    # Given Input
    N = 9
     
    # Function Call
    print(countWays(N))
 
# This code is contributed by ipg2016107


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Store perfect squares
// less than or equal to N
static List psquare;
 
// Utility function to calculate
// perfect squares <= N
private static void calcPsquare(int n)
{
    for(int i = 1; i * i <= n; i++)
        psquare.Add(i * i);
}
 
// DP array for memoization
private static int[,]dp;
 
// Recursive function to count
// number of ways to represent
// a number as a sum of perfect squares
private static int countWaysUtil(int index,
                                 int target)
{
     
    // Handle base cases
    if (target == 0)
        return 1;
    if (index < 0 || target < 0)
        return 0;
  
    // If already computed, return the result
    if (dp[index, target] != -1)
        return dp[index, target];
  
    // Else, compute the result
    return dp[index, target] = countWaysUtil(index,
                                             target - psquare[index]) +
                               countWaysUtil(index - 1, target);
}
 
// Function to find the number of ways to
// represent a number as a sum of perfect squares
private static int countWays(int n)
{
     
    // Precalculate perfect squares less
    // than or equal to N
    psquare = new List();
    calcPsquare(n);
  
    // Create dp array to memoize
    dp = new int[psquare.Count + 1, n + 1];
    for(int i = 0; i <= psquare.Count; i++)
    {
        for(int j = 0; j <= n; j++)
        {
            dp[i, j] = -1;
        }
         
        //Array.Fill(dp[i], -1);
    }
  
    // Function call to fill dp array
    return countWaysUtil(psquare.Count - 1, n);
}
 
// Driver Code
static void Main()
{
     
    // Given Input
    int N = 9;
 
    // Function Call
   Console.Write(countWays(N));
}
}
 
// This code is contributed by SoumikMondal


Javascript


输出:
4

时间复杂度: O(2 K ),其中 K 是小于或等于 N 的完全平方数
辅助空间: O(1)

高效的方法:这个问题有重叠的子问题和最优的子结构属性。为了优化上述方法,想法是通过使用大小为K*N的 2D 数组来记忆上述递归调用来使用动态编程,其中K是小于或等于N的完全平方数。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Store perfect squares
// less than or equal to N
vector psquare;
 
// Utility function to calculate
// perfect squares <= N
void calcPsquare(int N)
{
    for (int i = 1; i * i <= N; i++)
        psquare.push_back(i * i);
}
 
// DP array for memoization
vector > dp;
 
// Recursive function to count
// number of ways to represent
// a number as a sum of perfect squares
int countWaysUtil(int index, int target)
{
    // Handle base cases
    if (target == 0)
        return 1;
    if (index < 0 || target < 0)
        return 0;
 
    // If already computed, return the result
    if (dp[index][target] != -1)
        return dp[index][target];
 
    // Else, compute the result
    return dp[index][target]
           = countWaysUtil(
                 index, target - psquare[index])
 
             + countWaysUtil(
                   index - 1, target);
}
 
// Function to find the number of ways to
// represent a number as a sum of perfect squares
int countWays(int N)
{
    // Precalculate perfect squares less
    // than or equal to N
    calcPsquare(N);
 
    // Create dp array to memoize
    dp.resize(psquare.size() + 1,
              vector(N + 1, -1));
 
    // Function call to fill dp array
    return countWaysUtil(psquare.size() - 1, N);
}
 
// Driver Code
int main()
{
    // Given Input
    int N = 9;
 
    // Function Call
    cout << countWays(N);
 
    return 0;
}

Java

// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
public class GFG {
     
    // Store perfect squares
    // less than or equal to N
    private static ArrayList psquare;
 
     
    // Utility function to calculate
    // perfect squares <= N
    private static void calcPsquare(int n) {
 
        for (int i = 1; i * i <= n; i++)
            psquare.add(i * i);
         
    }
     
    // DP array for memoization
    private static int[][] dp;
     
    // Recursive function to count
    // number of ways to represent
    // a number as a sum of perfect squares
    private static int countWaysUtil(int index, int target) {
        // Handle base cases
        if (target == 0)
            return 1;
        if (index < 0 || target < 0)
            return 0;
      
        // If already computed, return the result
        if (dp[index][target] != -1)
            return dp[index][target];
      
        // Else, compute the result
        return dp[index][target]
               = countWaysUtil(
                     index, target - psquare.get(index))
      
                 + countWaysUtil(
                       index - 1, target);
    }
     
    // Function to find the number of ways to
    // represent a number as a sum of perfect squares
    private static int countWays(int n) {
        // Precalculate perfect squares less
        // than or equal to N
        psquare = new ArrayList();
        calcPsquare(n);
      
        // Create dp array to memoize
        dp = new int[psquare.size()+1][n+1];
        for(int i = 0; i<=psquare.size(); i++)Arrays.fill(dp[i], -1);
      
        // Function call to fill dp array
        return countWaysUtil(psquare.size() - 1, n);
    }
 
 
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given Input
        int N = 9;
 
        // Function Call
        System.out.print(countWays(N));
    }
     
}
 
// This code is contributed by Dheeraj Bhagchandani.

Python3

# Python3 program for the above approach
from math import sqrt
 
# Store perfect squares
# less than or equal to N
psquare = []
 
# DP array for memoization
dp = []
 
# Utility function to calculate
# perfect squares <= N
def calcPsquare(N):
     
    global psquare
    for i in range(1, int(sqrt(N)) + 1, 1):
        psquare.append(i * i)
 
# Recursive function to count
# number of ways to represent
# a number as a sum of perfect squares
def countWaysUtil(index, target):
     
    global dp
     
    # Handle base cases
    if (target == 0):
        return 1
    if (index < 0 or target < 0):
        return 0
 
    # If already computed, return the result
    if (dp[index][target] != -1):
        return dp[index][target]
 
    dp[index][target] = (countWaysUtil(
                               index, target - psquare[index]) +
                         countWaysUtil(index - 1, target))
 
    # Else, compute the result
    return dp[index][target]
 
# Function to find the number of ways to
# represent a number as a sum of perfect squares
def countWays(N):
     
    global dp
    global psquare
     
    # Precalculate perfect squares less
    # than or equal to N
    calcPsquare(N)
    temp = [-1 for i in range(N + 1)]
     
    # Create dp array to memoize
    dp = [temp for i in range(len(psquare) + 1)]
 
    # Function call to fill dp array
    return countWaysUtil(len(psquare) - 1, N) - 1
 
# Driver Code
if __name__ == '__main__':
     
    # Given Input
    N = 9
     
    # Function Call
    print(countWays(N))
 
# This code is contributed by ipg2016107

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Store perfect squares
// less than or equal to N
static List psquare;
 
// Utility function to calculate
// perfect squares <= N
private static void calcPsquare(int n)
{
    for(int i = 1; i * i <= n; i++)
        psquare.Add(i * i);
}
 
// DP array for memoization
private static int[,]dp;
 
// Recursive function to count
// number of ways to represent
// a number as a sum of perfect squares
private static int countWaysUtil(int index,
                                 int target)
{
     
    // Handle base cases
    if (target == 0)
        return 1;
    if (index < 0 || target < 0)
        return 0;
  
    // If already computed, return the result
    if (dp[index, target] != -1)
        return dp[index, target];
  
    // Else, compute the result
    return dp[index, target] = countWaysUtil(index,
                                             target - psquare[index]) +
                               countWaysUtil(index - 1, target);
}
 
// Function to find the number of ways to
// represent a number as a sum of perfect squares
private static int countWays(int n)
{
     
    // Precalculate perfect squares less
    // than or equal to N
    psquare = new List();
    calcPsquare(n);
  
    // Create dp array to memoize
    dp = new int[psquare.Count + 1, n + 1];
    for(int i = 0; i <= psquare.Count; i++)
    {
        for(int j = 0; j <= n; j++)
        {
            dp[i, j] = -1;
        }
         
        //Array.Fill(dp[i], -1);
    }
  
    // Function call to fill dp array
    return countWaysUtil(psquare.Count - 1, n);
}
 
// Driver Code
static void Main()
{
     
    // Given Input
    int N = 9;
 
    // Function Call
   Console.Write(countWays(N));
}
}
 
// This code is contributed by SoumikMondal

Javascript


输出
4

时间复杂度: O(K*N),其中 K 是小于或等于 N 的完全平方数
辅助空间: O(K*N)