数组可重复划分为和相等的子数组的次数


在 C++ 中,我们有一个 vector 头文件,可以在运行时更改数组的大小。在本文中,我们将学习数组可重复划分为和相等的子数组的次数的概念。

让我们举个例子来说明和相等的数组划分。

给定的数组是{1,2,3,4,2},我们将数组细分为两部分:

{1,2,3} - 数组每个索引的总和为6

{4,2} - 数组每个索引的总和为6

所以,给定数组可以划分为和相等的子数组2次。

算法

  • 我们将从名为‘iostream’‘vector’的头文件开始程序。

  • 现在我们开始创建名为‘isPartition_arr’的类来编写程序。

    在公共部分,声明名为‘isPartition_arr’的构造函数,它接受 num 作为参数来处理数组元素值。

  • 我们定义了一个名为‘cnt_Partition’的整型函数来计算数组可以划分的总次数。

  • 我们将变量‘sum’初始化为‘0’,稍后它将对数组进行求和,并将‘0’存储到变量‘count’中,该变量将跟踪数组元素递增计数。然后声明 for 循环以迭代‘arr’向量的每个元素。

  • 我们将变量‘current_sum’初始化为‘0’,并使用 for 循环迭代每个元素。

  • 完成 for 循环后,我们开始使用 while 循环迭代每个元素。

    如果‘current_sum’等于‘sum/2’,则计数将递增‘1’,并将‘current_sum’重置为‘0’。接下来,返回‘cnt’将计算数组可以细分为相等和的次数。

  • 我们从主函数开始,创建一个向量类型的整数‘num’来存储数组值。

  • 然后我们通过创建类的对象来传递‘num’值。接下来,我们调用函数‘cnt_partition’,获取对象并将其存储在变量 ‘c’ 中。

  • 最后,我们使用变量‘c’打印输出语句:“数组可以划分为两个和相等的子数组的次数”。

示例

在这个程序中,我们将找到数组可以重复划分为两个和相等的子数组的次数。

Open Compiler
#include <iostream> #include <vector> using namespace std; class isPartition_arr { public: vector<int> arr; isPartition_arr(vector<int>& num) { arr = num; } int cnt_Partition() { int sum = 0, count = 0; for (int i = 0; i < arr.size(); i++) { sum += arr[i]; } int current_sum = 0, j=0; while( j < arr.size() ) { current_sum += arr[j]; if (current_sum == sum / 2) { current_sum = 0; count++; } j++; } return count; } }; int main() { vector<int> num = {1, 2, 3, 4, 5, 5}; isPartition_arr A(num); int c = A.cnt_Partition(); cout <<"Number of times an array can be partitioned into\t"<< c <<"\t two subarrays with equal sum " << endl; return 0; }

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

Number of times an array can be partitioned into   2   two subarrays with equal sum 

结论

我们探讨了和相等的数组划分的概念,学习了如何将数组细分为不同的部分,并使总和相等。我们使用面向对象编程 (OOP) 的概念来解决这个问题,因为代码的可读性更好,并且可以有效地定义 C++ 程序。

更新于:2023年5月10日

浏览量:107

开启您的职业生涯

完成课程获得认证

开始学习
广告