LeetCode 之 jump-game-ii && binary-tree-postorder-traversal

1. 题目描述

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A =[2,3,1,1,4]

The minimum number of jumps to reach the last index is2. (Jump1step from index 0 to 1, then3steps to the last index.)

 思路:乍一看像动态规划,实际上更像是贪心算法。从左到右更新到达改点所需要的最短步数就能得到结果。

class Solution {
public:
    int jump(int A[], int n) {
        vector<int> dp(n,INT_MAX);
        dp[0] = 0;
        for(int i = 0;i<n; ++i){
            for(int j = 1;j<=A[i];++j){//在第i点所能到达的最远距离
                if( i+j <n && dp[i]+1 < dp[i+j]) dp[i+j] = dp[i]+1; //更新规则
            }
        }
        return dp[n-1];
    }
};

2. 题目描述

Given a binary tree, return the postorder traversal of its nodes' values.

For example:
Given binary tree{1,#,2,3},

   1
    \
     2
    /
   3

return[3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

思路:要求非递归实现后序遍历,而且是三种遍历中用非递归算法最难的一种。

     参考一些前人的经验,我在这里使用了一个unordered_set来标记第二次访问的节点(即左右根返回时的节点),整道题目的关键点就是使用stack来模拟递归,挺巧妙的一道题,也很容易忘。非递归前序和中序就相对简单多了,这里就不贴代码了。

     还有一种挺取巧的方法就是按照右左根的方式遍历,然后再reverse一下,挺巧妙的。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> res;
        if(root == nullptr) return res;
        stack<TreeNode *> s;
        unordered_set<TreeNode *> ss;
        TreeNode * p = root;
        while( p != nullptr || !s.empty()){
            while(p){
                s.push(p);
                p = p->left;
            }
            p = s.top();
            if(ss.count(p)) {
                res.push_back(p->val);
                s.pop();
                p = nullptr;
            }else {
                ss.insert(p);
                p = p->right;
            }
        }
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/J1ac/p/9439592.html