📣 黑五价提前开抢|VIP一年通行证5折,蓝莓、Offer多多同步特惠
查看: 1528| 回复: 2
跳转到指定楼层
上一主题 下一主题
收起左侧

[树/链表/图] 一道体现了DFS哲学思想的解答

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
本帖最后由 codedayday 于 2021-1-30 18:30 编辑

欢迎去下面讨论:
https://leetcode.com/problems/ve ... th-the-end-in-mind-(%22The-7-Habits-of-Highly-Effective-People%22)


或者我贴在这里,非常欢迎大家的意见。
DFS = Begin with the end in mind  ("The 7 Habits of Highly Effective People")
One of hard part to understand recursion function is that when you creat a dfs function and you need assume dfs is already there good to be used.
It is a wonderful chick-egg dilemma.


  1. class Solution {
  2. public:
  3.     vector<vector<int>> verticalTraversal(TreeNode* root) {
  4.         map<int, map<int, multiset<int> > > m;
  5.         dfs(root, 0, 0, m); // step1:  consume dfs function first
  6.         vector<vector<int>> ans;
  7.         for(auto& [col, rowAndVals]: m){ // step 2: consume m and begin with smallest/leftmost col index
  8.             vector<int> rowVec;
  9.             for(auto& [row, Vals]: rowAndVals) // step 3: top-down and begin with smallest/topmost row index
  10.                 rowVec.insert(rowVec.end(), Vals.begin(), Vals.end());//step 4: multiset is used to ensure order
  11.             ans.push_back(rowVec);
  12.         }
  13.         return ans;        
  14.     }
  15.    
  16. private: // step 4: pre-order traverse binary tree and log
  17.     void dfs(TreeNode* root, int row, int col, map<int, map<int, multiset<int> > >& m){
  18.         if(!root) return;
  19.         m[col][row].insert(root->val);
  20.         dfs(root->left,  row + 1, col - 1, m);
  21.         dfs(root->right, row + 1, col + 1, m);
  22.     }
  23. };
复制代码





上一篇:关于CS61a
下一篇:有人组队一起刷leetcode么
推荐
usr_opta 2021-1-31 12:50:07 | 只看该作者
全局:
这里不存在逻辑意义上的 delimma,递归算法的正确性由数学归纳法证明,至于数学归纳法的正确性,本身就可以视作公理。
回复

使用道具 举报

🔗
 楼主| codedayday 2021-1-31 13:08:59 | 只看该作者
全局:
usr_opta 发表于 2021-1-30 20:50
这里不存在逻辑意义上的 delimma,递归算法的正确性由数学归纳法证明,至于数学归纳法的正确性,本身就可以 ...

为你教科书式的规范发言,点赞。
这也是为什么我们需要top-down系统学习理论。


对于bottum-up 从实践 到理论的理解方式,很多人,包括我,也是在做了很多题以后才悟出这个道理:
别怂,梭哈就对了: Don't doubt, just believe.

当然, 背后根源在于 “数学归纳法”

top-down  和  bottum-up从两个角度展现递归之美:)
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表