您的位置:首页 > 其它

leetcode 207. Course Schedule

2017-03-31 22:15 423 查看
难度:Medium

There are a total of n courses you have to take, labeled from
0
to
n - 1
.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair:
[0,1]


Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

For example:

2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

2, [[1,0],[0,1]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

题解:一开始是考虑将所有的出现过的点压入一个vector 然后看所有点的入度 因为本质上这个问题就是一个找图里面环的问题 后来发现找错了方向 其实直接考虑前后位置就可以

这样用两个for循环就可以了 复杂度是n^2

代码如下:

class Solution {
public:

bool canFinish(int num, vector<pair<int, int>>& vec) {
for(int i=0;i<vec.size();i++)
{
int number=vec[i].second;
for(int k=0;k<vec.size();k++)
{
if(vec[k].first==vec[i].first)
continue;
else if(vec[k].first==number)
{
number=vec[k].second;
if(number==vec[i].first)
return false;
}
}
}
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: