C++ 代码以检查全部灯泡是否可以被开启
假设我们有一个数字 m 和一个包含 n 个子列表的嵌套列表 A。考虑有 m 个灯泡,最初它们全部关闭。有 n 个按钮,每个按钮都连接到一些灯泡。所以 A[i] 是一组灯泡,可以通过按下第 i 个开关打开。我们必须检查我们是否可以点亮所有灯泡。
所以,如果输入像 A = [[1, 4], [1, 3, 1], [2]];m = 4,则输出将为 True,因为通过按下所有开关,我们可以点亮全部四个灯泡。
步骤
为了解决这个问题,我们将遵循这些步骤 −
Define one set s for initialize i := 0, when i < size of A, update (increase i by 1), do: for initialize j := 0, when j < size of A[i], update (increase j by 1), do: insert A[i, j] into s if size of s is same as m, then: return true Otherwise return false
示例
让我们看看以下实现以获得更好的理解 −
#include <bits/stdc++.h>
using namespace std;
bool solve(vector<vector<int>> A, int m){
set<int> s;
for (int i = 0; i < A.size(); i++){
for (int j = 0; j < A[i].size(); j++){
s.insert(A[i][j]);
}
}
if (s.size() == m)
return true;
else
return false;
}
int main(){
vector<vector<int>> A = { { 1, 4 }, { 1, 3, 1 }, { 2 } };
int m = 4;
cout <<solve(A, m) << endl;
}输入
{ { 1, 4 }, { 1, 3, 1 }, { 2 } }, 4输出
1
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP