卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章17932本站已运行3328

一个数组可以重复分割成具有相等和的子数组的次数

一个数组可以重复分割成具有相等和的子数组的次数

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

Let’s take an example to show an array partition with an equal sum.

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

{1,2,3}- The total sum of each index of an array is 6.

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

所以,给定数组的数量的2倍可以被分割成具有相等和的子数组。

Algorithm

  • 我们将以头文件‘iostream’‘vector’开始程序。

  • Now we start the program by creating a class named ‘isPartition_arr’.

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

  • We are defining a function named ‘cnt_Partition’ of integer type to calculate the total number of times an array can be partitioned.

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

  • We are initializing the variable ‘current_sum’ to ‘0’ and iterating over each element using for loop.

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

    如果‘current_sum’等于‘sum/2’,那么计数将增加‘1’并将‘current_sum’重置为‘0’。接下来,返回‘cnt’将计算数组可以被等分的次数。

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

  • Then we pass the ‘num’ value by creating the object of the class. Next, we call the function ‘cnt_partition’ by taking the object and storing it in the variable ‘c’.

  • Finally, we print the output statement as “Number of times of an array can be partitioned into two subarrays with equal sum” with the help of variable ‘c’.

Example

的中文翻译为:

示例

在这个程序中,我们将找到一个数组可以被重复分割成两个子数组,使得它们的和相等的次数。

'
#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 intot"<< c <<"t two subarrays with equal sum " << endl;
   return 0;
}

Output

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

结论

我们探索了等和数组划分的概念,学习了如何将数组分割成不同的部分,并使总和相等。我们使用面向对象的概念来解决这个问题,因为代码的可读性更好,并且能够高效地定义一个C++程序。

卓越飞翔博客
上一篇: 如何使用Nginx代理实现Web服务的负载均衡?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏