C++程序:获取n倍复制序列中最长子序列的长度


假设我们有一个包含n个元素的数组A。我们可以创建一个新的数组,该数组由n个旧数组的副本组成,元素首尾相连。我们必须找到新数组中最长递增子序列的长度?我们知道,如果p可以通过移除b中的零个或多个元素来获得,则序列p是数组b的子序列。数组的最长递增子序列是其元素按严格递增顺序排列的最长子序列。

问题类别

在数据结构中,数组是特定类型元素的有限集合。数组用于在连续的内存位置存储相同类型的元素。数组被分配一个特定的名称,并在各种编程语言中通过该名称引用。要访问数组的元素,需要索引。我们使用术语“name[i]”来访问数组“name”中位于位置“i”的特定元素。可以使用数组实现各种数据结构,例如堆栈、队列、堆和优先队列。数组的操作包括插入、删除、更新、遍历、搜索和排序操作。请访问下面的链接以了解更多信息。

https://tutorialspoint.com/data_structures_algorithms/array_data_structure.htm

因此,如果我们问题的输入类似于A = [3, 1, 4, 1, 5, 9],则输出将为5,因为可能的子序列将为[1, 3, 4, 5, 9]。

步骤

为了解决这个问题,我们将遵循以下步骤:

Define one set s
for initialize i := 0, when i < size of A, update (increase i by 1), do:
   insert A[i] into s
return size of s

示例

让我们看下面的实现来更好地理解:

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> A){
   set<int> s;
   for (int i = 0; i < A.size(); i++){
      s.insert(A[i]);
   }
   return s.size();
}
int main(){
   vector<int> A = { 3, 1, 4, 1, 5, 9 };
   cout << solve(A) << endl;
}

输入

{ 3, 1, 4, 1, 5, 9 }

输出

5

更新于:2022年4月8日

157 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.