• 进程终止(你真的学会递归了吗?考验你的递归基础)


    1.对应lintcode链接:

    872 · 终止进程 - LintCode

    2.题目描述:

     3.解题思路:

    方法一:⭐⭐⭐

    通过追溯父节点来判断一个节点的祖先节点中是否含有kill:

    1.生成一个父亲表每个子进程可以通过id找到对应的父进程的id。

    2.遍历子进程的数组从自己的id开始通过父亲表一直往上看能不能和kill的值一样如果一样就将其加入到答案中。

    4.对应代码:

    1. class Solution {
    2. public:
    3. /**
    4. * @param pid: the process id
    5. * @param ppid: the parent process id
    6. * @param kill: a PID you want to kill
    7. * @return: a list of PIDs of processes that will be killed in the end
    8. * we will sort your return value in output
    9. */
    10. vector<int> killProcess(vector<int> &pid, vector<int> &ppid, int kill) {
    11. // Write your code here
    12. unordered_map<int,int>Parent;
    13. //通过子进程的pid能够找到父进程的pid
    14. for(int i=0;i<pid.size();i++)
    15. {
    16. Parent[pid[i]]=ppid[i];
    17. }
    18. vector<int>ans{kill};//用于收集答案
    19. for(auto ch:pid)//遍历子进程的pid
    20. {
    21. int k=ch;
    22. int temp=k;
    23. while(k!=0)//通过父亲表开始一直往上走
    24. {
    25. if(Parent[k]==kill){
    26. ans.push_back(temp);
    27. break;
    28. }
    29. //获取自己的父进程的id
    30. k=Parent[k];
    31. }
    32. }
    33. return ans;
    34. }
    35. };

    但是了这种时间复杂度比较高下面我们来看另外一种方法:回溯

    方法二⭐⭐⭐⭐⭐⭐

    1.定义一个孩子表父进程通过自己的pid可以找到它所有的子进程的pid

    2.dfs遍历每个子进程的子进程直到遍历结束。

    对应代码:

    1. class Solution {
    2. public:
    3. /**
    4. * @param pid: the process id
    5. * @param ppid: the parent process id
    6. * @param kill: a PID you want to kill
    7. * @return: a list of PIDs of processes that will be killed in the end
    8. * we will sort your return value in output
    9. */
    10. vector<int> killProcess(vector<int> &pid, vector<int> &ppid, int kill) {
    11. // Write your code here
    12. unordered_map<int,vector<int>>child;//父进程id对应它的孩子节点
    13. int N=ppid.size();
    14. for(int i=0;i<N;i++)
    15. {
    16. if(!child.count(ppid[i])){
    17. child[ppid[i]]=vector<int>();
    18. }
    19. child[ppid[i]].push_back(pid[i]);
    20. }
    21. vector<int>ans;
    22. dfs(ans,child,kill);
    23. return ans;
    24. }
    25. void dfs(vector<int>&ans,unordered_map<int,vector<int>>&child,int kill)
    26. {
    27. ans.push_back(kill);
    28. if(child.count(kill))//看有没有子进程的pid
    29. {
    30. for(auto x:child[kill])//遍历其孩子节点
    31. {
    32. dfs(ans,child,x);
    33. }
    34. }
    35. }
    36. };

  • 相关阅读:
    等保2.0密码要求是什么?法律依据有哪些?
    参数化建模 vs. 直接建模【CAD】
    html总结-1-结构与常见标签
    2022CCPC广州
    vue+Fullcalendar
    Speech | 语音处理,分割一段音频(python)
    软件开发工具的技术要素
    Android 恢复出厂设置时间重置
    【Redis】集群存储算法
    jQuery_显式迭代each()
  • 原文地址:https://blog.csdn.net/qq_56999918/article/details/125475361