210. Course Schedule II\199. Binary Tree Right Side View\279. Perfect Squares

来源:互联网 发布:网络推手成名的网红 编辑:程序博客网 时间:2024/06/05 09:00

  • Course Schedule II
    • DESCRIPTION
    • IMPLEMENTATION
  • Binary Tree Right Side View
    • DESCRIPTION
    • IMPLEMENTATION
  • Perfect Squares
    • DESCRIPTION
    • IMPLEMENTATION

210. Course Schedule II

DESCRIPTION

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, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

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 the correct course order is [0,1]
4, [[1,0],[2,0],[3,1],[3,2]]There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].

Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.

You may assume that there are no duplicate edges in the input prerequisites.

In this problem, it’s a kind of edge presentation, but I change it to adjacent matrix. Then I use BFS to to through all the nodes which is close to this no in-degree edge and after this operation, I utilize the the left nodes to do the recursive step when all nodes is visited.

So the whole algorithm can be shown below:

1 calculate the in-degree for each node
2 go through all the nodes which contain in-degree = 0 and push it into a queue if no this kind of edge, break
2.1 pop the top element elei and push it into the result vector.
2.2 set the elei to visited and visit all the nodes that is adjacent to elei.
3 if the vector has the size the same as the number of courses, return the result. Otherwise, return empty vector.

IMPLEMENTATION

The code shows below:

class Solution {public:    int getNextCourse(vector<int>& rec, int num) {        int res = num;        for(int idx = 0; idx < num; ++idx)             if(!rec[idx])                 return idx;        return res;    }    vector<int> findOrder(int numCourses, vector<pair<int, int>>& pre) {        vector<int> res;        vector<vector<bool>> board(numCourses, vector<bool>(numCourses, 0));        vector<int> rec(numCourses, 0);        int num_edge = pre.size();        for(int idx = 0; idx < num_edge; idx++) {             board[pre[idx].first][pre[idx].second] = true;            rec[pre[idx].first]++;        }            queue<int> cur_course;        int idx = 0;        while((idx = getNextCourse(rec, numCourses)) != numCourses) {            cur_course.push(idx);            while(!cur_course.empty()) {                int tp = cur_course.front();                cur_course.pop();                res.push_back(tp);                for(int idx2 = 0; idx2 < numCourses; idx2++)                     if(board[idx2][idx]) {                        rec[idx2]--;                    }            }                rec[idx] = -1;        }        return res.size() == numCourses? res:vector<int>();    }};

199. Binary Tree Right Side View

DESCRIPTION

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

For example:
Given the following binary tree,

   1            <--- /   \2     3         <--- \     \  5     4       <---

You should return [1, 3, 4].

We analyse this problem and find that this result is always the right most node in the tree, we can use BFS go through the tree, and in every level, the first visited node is the right-most leaf node.

So the whole steps can be described below:

1 if the root is not empty, push into the queue
2 go through the whole tree with BFS(but the right leaf node is visited firstly then the left node)
2.1 pop the first front of the queue and push its leaves into queue if necessary.
2.2 go through the left queue in the same level and do the operation as 2.1
3 return the result.

IMPLEMENTATION

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector<int> rightSideView(TreeNode* root) {        vector<int> res;        queue<TreeNode*> que;        if(root)  que.push(root);        while(!que.empty()) {            int num = que.size();            TreeNode* tp = que.front();            res.push_back(tp->val);            que.pop();            if(tp->right) que.push(tp->right);            if(tp->left) que.push(tp->left);            for(int idx = 1; idx < num; ++idx) {                tp = que.front();                que.pop();                if(tp->right) que.push(tp->right);                if(tp->left) que.push(tp->left);            }        }        return res;    }};

279. Perfect Squares

DESCRIPTION

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, …) which sum to n.

For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.

In this problem, we calculate the minimal number of squared number to sum up the target.

Here I think this problem is similar to the coin problem in dynamic programming.

So my algorithm is shown below:

1 malloc a array as large as the number n + 1 with initialization with -1. (-1 indicate there is no way to this number. ) Set rec[n] to 0.
2 go through every node below n with indicate idx.
2.1 go through the ceil(sqrt(idx)) to 1 with variable sed
2.2 update the rec[idx - sed*sed] with state translation rec[idx-sed] = min(rec[idx-sed], rec[idx]+1);
3 return the result.

IMPLEMENTATION

The code can be implemented as below:

And from the path idea, it seem we can use BFS to do it.

class Solution {public:    int numSquares(int n) {        vector<int> rec(n + 1, -1);        rec[n] = 0;        for(int tp = n; tp >= 1; tp--) {            for(int idx = ceil(sqrt(tp)); idx >= 1; idx--) {                if(rec[tp] != -1) {                int square = idx*idx;                int ind = tp - square;                if(ind >= 0) {                    if(rec[ind] == -1) rec[ind] = rec[tp] + 1;                    else rec[ind] = min(rec[tp]+1, rec[ind]);                }                    }            }        }            return rec[0];    }};
0 0
原创粉丝点击