Find all combinations of perfect squares that sum up to N with duplicates
Last Updated :
14 Jan, 2022
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++
#include <bits/stdc++.h>
using namespace std;
void combinationSum(
vector< int > list, int N,
int ind, vector< int > perfSquares)
{
if (N < 0 || ind == list.size())
return ;
if (N == 0)
{
for ( int i : perfSquares)
{
cout << i << " " ;
}
cout << endl;
return ;
}
combinationSum(list, N,
ind + 1, perfSquares);
perfSquares.push_back(list[ind]);
combinationSum(list, N - list[ind],
ind, perfSquares);
perfSquares.pop_back();
}
void sumOfPerfectSquares( int N)
{
vector< int > list;
int sqrtN = ( int )( sqrt (N));
for ( int i = 1; i <= sqrtN; i++)
{
list.push_back(i * i);
}
vector< int > perfSquares;
combinationSum(list, N, 0,
perfSquares);
}
int main()
{
int N = 8;
sumOfPerfectSquares(N);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
import java.lang.Math;
class GFG {
public static void
sumOfPerfectSquares( int N)
{
ArrayList<Integer> list = new ArrayList<>();
int sqrtN = ( int )(Math.sqrt(N));
for ( int i = 1 ; i <= sqrtN; i++) {
list.add(i * i);
}
combinationSum(list, N, 0 ,
new ArrayList<>());
}
static void combinationSum(
List<Integer> list, int N,
int ind, List<Integer> perfSquares)
{
if (N < 0 || ind == list.size())
return ;
if (N == 0 ) {
for ( int i : perfSquares) {
System.out.print(i + " " );
}
System.out.println();
return ;
}
combinationSum(list, N,
ind + 1 , perfSquares);
perfSquares.add(list.get(ind));
combinationSum(list, N - list.get(ind),
ind, perfSquares);
perfSquares.remove(perfSquares.size() - 1 );
}
public static void main(String[] args)
{
int N = 8 ;
sumOfPerfectSquares(N);
}
}
|
Python3
import math
def combinationSum(lst, N, ind, perfSquares):
if N < 0 or ind = = len (lst):
return
if N = = 0 :
for i in perfSquares:
print (i, end = ' ' )
print ('')
return ;
combinationSum(lst,N,ind + 1 ,perfSquares)
perfSquares.append(lst[ind])
combinationSum(lst, N - lst[ind], ind, perfSquares)
perfSquares.pop()
def sumOfPerfectSquares(N):
lst = []
sqrtN = int (math.sqrt(N))
for i in range ( 1 , sqrtN + 1 ):
lst.append(i * i)
perfSquares = []
combinationSum(lst, N, 0 , perfSquares)
N = 8
sumOfPerfectSquares(N)
|
C#
using System;
using System.Collections.Generic;
class GFG {
public static void sumOfPerfectSquares( int N)
{
List< int > list = new List< int >();
int sqrtN = ( int )(Math.Sqrt(N));
for ( int i = 1; i <= sqrtN; i++) {
list.Add(i * i);
}
combinationSum(list, N, 0, new List< int >());
}
static void combinationSum(List< int > list, int N,
int ind,
List< int > perfSquares)
{
if (N < 0 || ind == list.Count)
return ;
if (N == 0) {
foreach ( int i in perfSquares)
{
Console.Write(i + " " );
}
Console.WriteLine();
return ;
}
combinationSum(list, N, ind + 1, perfSquares);
perfSquares.Add(list[ind]);
combinationSum(list, N - list[ind], ind,
perfSquares);
perfSquares.RemoveAt(perfSquares.Count - 1);
}
public static void Main( string [] args)
{
int N = 8;
sumOfPerfectSquares(N);
}
}
|
Javascript
<script>
function combinationSum(list, N, ind, perfSquares)
{
if (N < 0 || ind == list.length)
return ;
if (N == 0)
{
for (let i = 0; i < perfSquares.length; i++)
{
document.write(perfSquares[i] + " " );
}
document.write( "\n" );
return ;
}
combinationSum(list, N,
ind + 1, perfSquares);
perfSquares.push(list[ind]);
combinationSum(list, N - list[ind],
ind, perfSquares);
perfSquares.pop();
}
function sumOfPerfectSquares(N)
{
let list = [];
let sqrtN = Math.sqrt(N);
for (let i = 1; i <= sqrtN; i++)
{
list.push(i * i);
}
let perfSquares = [];
combinationSum(list, N, 0,
perfSquares);
}
let N = 8;
sumOfPerfectSquares(N);
</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)
Share your thoughts in the comments
Please Login to comment...