📌  相关文章
📜  找到所有完美平方的组合,其总和为 N 并带有重复项

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

找到所有完美平方的组合,其总和为 N 并带有重复项

给定一个正整数N ,任务是打印所有可能的完美平方和,使得所有完美平方的总和等于N。

例子:

方法:给定的问题可以使用递归和回溯来解决。这个想法是生成一个小于N的完美平方列表,然后计算等于N的完美平方和的可能组合。在递归函数中,在每个索引处,可以为列表选择或不选择元素.请按照以下步骤解决问题:

  • 初始化一个 ArrayList 以存储所有小于N的完美平方
  • 将整数N从 1 迭代到N的平方根 使用变量i
    • 如果i的平方小于或等于N,则将i * i添加到列表中
  • 使用递归和回溯计算等于N的完美平方和
  • 在每个索引 以下:
    • 不要在当前索引处包含元素并递归调用下一个索引
    • 在当前索引处包含元素并对同一索引进行递归调用
  • 递归函数需要以下两种基本情况:
    • 如果N小于零,或者如果ind到达列表末尾,则返回
    • 如果N变为零,则打印列表

下面是上述方法的实现:

C++
// C++ code for the above approach
#include 
using namespace std;
 
// Function to print all combinations of
// sum of perfect squares equal to N
void combinationSum(
    vector list, int N,
    int ind, vector 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 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 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 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 list, int N,
        int ind, List 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 list = new List();
        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());
    }
 
    // Function to print all combinations of
    // sum of perfect squares equal to N
    static void combinationSum(List list, int N,
                               int ind,
                               List 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


输出
4 4 
1 1 1 1 4 
1 1 1 1 1 1 1 1 

时间复杂度: O(N * 2^N),其中 N 是给定的数字
辅助空间: O(N)