Open In App

Find all combinations of perfect squares that sum up to N with duplicates

Last Updated : 14 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a positive integer N, the task is to print all possible sum of perfect squares such that the total sum of all perfect squares is equal to N.

Example:

Input: N=8
Output: 4 4
              1 1 1 1 4
              1 1 1 1 1 1 1 1 
Explanation: There are three possible ways to make sum equal to N

Input: N=3
Output: 1 1 1

 

Approach: The given problem can be solved using recursion and backtracking. The idea is to generate a list of perfect squares less than N, then calculate the possible combinations of perfect squares sum which are equal to N. In the recursive function, at every index either the element can be chosen for the list or not be chosen. Follow the steps below to solve the problem:

  • Initialize an ArrayList to store all perfect squares less than N
  • Iterate the integer N from 1 to square root of N using variable i
    • If the square of i is less than or equal to N, then add i * i into the list
  • Use recursion and backtracking to calculate sum of perfect squares that are equal to N
  • At every index ind do the following:
    • Do not include element at the current index and make a recursive call to the next index
    • Include the element at current index and make a recursive call on the same index
  • Following two base cases will be needed for the recursive function:
    • If N becomes less than zero, or if ind reached the end of list then return
    • If N becomes equal to zero then print the list

Below is the implementation of the above approach:
 

C++




// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to print all combinations of
// sum of perfect squares equal to N
void combinationSum(
    vector<int> list, int N,
    int ind, vector<int> perfSquares)
{
 
    // Sum of perfect squares exceeded N
    if (N < 0 || ind == list.size())
        return;
 
    // Sum of perfect squares is equal to N
    // therefore a combination is found
    if (N == 0)
    {
 
        for (int i : perfSquares)
        {
            cout << i << " ";
        }
        cout << endl;
        return;
    }
 
    // Do not include the current element
    combinationSum(list, N,
                   ind + 1, perfSquares);
 
    // Include the element at current index
    perfSquares.push_back(list[ind]);
 
    combinationSum(list, N - list[ind],
                   ind, perfSquares);
 
    // Remove the current element
    perfSquares.pop_back();
}
 
// Function to check whether the
// number is a perfect square or not
void sumOfPerfectSquares(int N)
{
 
    // Initialize an arraylist to store
    // all perfect squares less than N
    vector<int> list;
    int sqrtN = (int)(sqrt(N));
 
    // Iterate till square root of N
    for (int i = 1; i <= sqrtN; i++)
    {
 
        // Add all perfect squares
        // to the list
        list.push_back(i * i);
    }
    vector<int> perfSquares;
    combinationSum(list, N, 0,
                   perfSquares);
}
 
// Driver code
int main()
{
    int N = 8;
 
    // Call the function
    sumOfPerfectSquares(N);
    return 0;
}
 
// This code is contributed by Potta Lokesh


Java




// Java implementation for the above approach
 
import java.io.*;
import java.util.*;
import java.lang.Math;
 
class GFG {
 
    // Function to check whether the
    // number is a perfect square or not
    public static void
    sumOfPerfectSquares(int N)
    {
 
        // Initialize an arraylist to store
        // all perfect squares less than N
        ArrayList<Integer> list = new ArrayList<>();
        int sqrtN = (int)(Math.sqrt(N));
 
        // Iterate till square root of N
        for (int i = 1; i <= sqrtN; i++) {
 
            // Add all perfect squares
            // to the list
            list.add(i * i);
        }
 
        combinationSum(list, N, 0,
                       new ArrayList<>());
    }
 
    // Function to print all combinations of
    // sum of perfect squares equal to N
    static void combinationSum(
        List<Integer> list, int N,
        int ind, List<Integer> perfSquares)
    {
 
        // Sum of perfect squares exceeded N
        if (N < 0 || ind == list.size())
            return;
 
        // Sum of perfect squares is equal to N
        // therefore a combination is found
        if (N == 0) {
 
            for (int i : perfSquares) {
                System.out.print(i + " ");
            }
            System.out.println();
            return;
        }
 
        // Do not include the current element
        combinationSum(list, N,
                       ind + 1, perfSquares);
 
        // Include the element at current index
        perfSquares.add(list.get(ind));
 
        combinationSum(list, N - list.get(ind),
                       ind, perfSquares);
 
        // Remove the current element
        perfSquares.remove(perfSquares.size() - 1);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int N = 8;
 
        // Call the function
        sumOfPerfectSquares(N);
    }
}


Python3




# Python code for the above approach
  
# Function to print all combinations of
# sum of perfect squares equal to N
import math
 
def combinationSum(lst, N, ind, perfSquares):
   
    # Sum of perfect squares exceeded N
    if N < 0 or ind == len(lst):
        return
     
    # Sum of perfect squares is equal to N
    # therefore a combination is found
    if N == 0:
        for i in perfSquares:
            print(i, end = ' ')
        print('')
        return;
     
    # Do not include the current element
    combinationSum(lst,N,ind+1,perfSquares)
     
    # Include the element at current index
    perfSquares.append(lst[ind])
     
    combinationSum(lst, N  - lst[ind], ind, perfSquares)
     
    # Remove the current element
    perfSquares.pop()
     
# Function to check whether the
# number is a perfect square or not   
def sumOfPerfectSquares(N):
   
    # Initialize an arraylist to store
    # all perfect squares less than N
    lst = []
    sqrtN = int(math.sqrt(N))
     
    # Iterate till square root of N
    for i in range(1, sqrtN + 1):
       
        # Add all perfect squares
        # to the list
        lst.append(i*i)
     
    perfSquares = []
    combinationSum(lst, N, 0, perfSquares)
 
# Driver code   
N = 8
 
# Call the function
sumOfPerfectSquares(N)
 
# This code is contributed by rdtank.


C#




// C# implementation for the above approach
using System;
using System.Collections.Generic;
 
class GFG {
 
    // Function to check whether the
    // number is a perfect square or not
    public static void sumOfPerfectSquares(int N)
    {
 
        // Initialize an arraylist to store
        // all perfect squares less than N
        List<int> list = new List<int>();
        int sqrtN = (int)(Math.Sqrt(N));
 
        // Iterate till square root of N
        for (int i = 1; i <= sqrtN; i++) {
 
            // Add all perfect squares
            // to the list
            list.Add(i * i);
        }
 
        combinationSum(list, N, 0, new List<int>());
    }
 
    // Function to print all combinations of
    // sum of perfect squares equal to N
    static void combinationSum(List<int> list, int N,
                               int ind,
                               List<int> perfSquares)
    {
 
        // Sum of perfect squares exceeded N
        if (N < 0 || ind == list.Count)
            return;
 
        // Sum of perfect squares is equal to N
        // therefore a combination is found
        if (N == 0) {
 
            foreach(int i in perfSquares)
            {
                Console.Write(i + " ");
            }
            Console.WriteLine();
            return;
        }
 
        // Do not include the current element
        combinationSum(list, N, ind + 1, perfSquares);
 
        // Include the element at current index
        perfSquares.Add(list[ind]);
 
        combinationSum(list, N - list[ind], ind,
                       perfSquares);
 
        // Remove the current element
        perfSquares.RemoveAt(perfSquares.Count - 1);
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        int N = 8;
 
        // Call the function
        sumOfPerfectSquares(N);
    }
}
 
// This code is contributed by ukasp.


Javascript




<script>
// Javascript code for the above approach
 
// Function to print all combinations of
// sum of perfect squares equal to N
function combinationSum(list, N, ind, perfSquares)
{
 
    // Sum of perfect squares exceeded N
    if (N < 0 || ind == list.length)
        return;
 
    // Sum of perfect squares is equal to N
    // therefore a combination is found
    if (N == 0)
    {
 
        for (let i = 0; i < perfSquares.length; i++)
        {
            document.write(perfSquares[i] + " ");
        }
        document.write("\n");
        return;
    }
 
    // Do not include the current element
    combinationSum(list, N,
                   ind + 1, perfSquares);
 
    // Include the element at current index
    perfSquares.push(list[ind]);
 
    combinationSum(list, N - list[ind],
                   ind, perfSquares);
 
    // Remove the current element
    perfSquares.pop();
}
 
// Function to check whether the
// number is a perfect square or not
function sumOfPerfectSquares(N)
{
 
    // Initialize an arraylist to store
    // all perfect squares less than N
    let list = [];
    let sqrtN = Math.sqrt(N);
 
    // Iterate till square root of N
    for (let i = 1; i <= sqrtN; i++)
    {
 
        // Add all perfect squares
        // to the list
        list.push(i * i);
    }
    let perfSquares = [];
    combinationSum(list, N, 0,
                   perfSquares);
}
 
// Driver code
  let N = 8;
 
    // Call the function
    sumOfPerfectSquares(N);
 
// This code is contributed by Samim Hossain Mondal.
</script>


Output

4 4 
1 1 1 1 4 
1 1 1 1 1 1 1 1 

Time Complexity: O(N * 2^N), Where N is the number given
Auxiliary Space: O(N)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads