面试 leecode

面试 leecode

一、idea leecode插件安装及配置

1. 安装

IDEA插件安装套路

2. 配置

原配置

//code fileName 
[$!{question.frontendQuestionId}]${question.title}
//code template
${question.content}

${question.code}
//templact constant
${question.title}	题目标题	示例:两数之和
${question.titleSlug}	题目标记	示例:two-sum
${question.frontendQuestionId}	题目编号
${question.content}	题目描述
${question.code}	题目代码
$!velocityTool.camelCaseName(str)	转换字符为大驼峰样式(开头字母大写)
$!velocityTool.smallCamelCaseName(str)	转换字符为小驼峰样式(开头字母小写)
$!velocityTool.snakeCaseName(str)	转换字符为蛇形样式
$!velocityTool.leftPadZeros(str,n)	在字符串的左边填充0,使字符串的长度至少为n
$!velocityTool.date()	获取当前时间

改成如下:

  1. //code fileName 
  2. $!velocityTool.camelCaseName(${question.titleSlug}) 
  3. //code template 
  4. ${question.content} 
  5. public class $!velocityTool.camelCaseName(${question.titleSlug}){ 
  6. public static void main(String[] args) { 
  7. Solution solution = new $!velocityTool.camelCaseName(${question.titleSlug})().new Solution(); 
  8.  
  9. } 
  10.  
  11. ${question.code} 
  12. } 

3. 问题

3-1. 题目中文乱码

idea安装文件vmoptions里增加-Dfile.encoding=utf-8

二、B占左神7天刷题

1. 基础班

1-1. 面试技巧(P1)

1-1-1. 刷题5大问题

  1. 书看不懂,吃灰
  2. 简单题过了,中难题写不出来,题看不明白
  3. 问题问题关联上某个算法和结构,搜到帖子,看不懂,想起了书(算法导论)
  4. 中等题也能写出来,难的算法题,还是门都没找到
  5. 不学不看算法,不做算法的工作,某个特定业务,某个算法比你的代码性能提高数倍。
  • 帖子难懂
  • 书难懂
  • 知识体系不足

1-2. 复杂度和简单排序算法(P2)

1-2-1. 复杂度

1-2-1-1. 时间复杂度
  1. 常数时间复杂度:如果和数据量没关系,叫做常数操作就是流程中的行为节点(int a=arr[i])
  2. 时间复杂度是算法流程中,常数操作数量的指标,发生多少常数操作
  3. 常数操作数量的表达式(int b=list.get(i) )只要高阶项,不要系数,然后就是时间复杂度O(f(n))
  4. 算法流程好坏先看时间复杂度,再看不同数据样本下的常数项时间:不同结构执行时间不同。比如找数数组要比list快。
1-2-1-2. 简单排序算法
  • 常数操作(流程中)
    1. 找数
    2. 比较大小
    3. 交换
  • 常数操作次数(常数操作数量)
    1. 找数N+N-1+N-2+...
    2. 比较N+N-1+N-2+...
    3. swap:N次
      一共常数操作次数表达式:aN^2+bN+c
  • 根据表达式获取复杂度原则舍弃bN+C忽略a得到的是N2得到O(N2) O在数学上是上限的含义

总结:评估性能的两个指标:时间复杂度,常数项执行时间

两个常数项时间不同的代码要实际跑才能看出优劣跟空间有关系
两个常数项时间不同的代码要实际跑才能看出优劣跟空间有关系

O最差,(-) 是平均,Ω是最优时间复杂度插入排序的最优是O(N)

1-2-1-3. 二分法O(logN)其实就是2为底
  1. 有序数组,某个数是否存在
  2. 在一个有序数组中,找>=某个数最左侧的位置
  3. 局部最小值问题
1-2-1-4. 对数器的概念和使用
  1. 有一个想要测的方法a
  2. 实现复杂度不好但是容易实现的方法b
  3. 实现一个随机样本产生器
  4. 把方法a和方法b跑相同的随机样本,看看结果是否一样
  5. 如果有一个随机样本使得对比结果不一致,打印样本进行人工干预,改对方法a或者方法b
  6. 当样本数量很多时对比测试一样正确,可以确认方法a已经正确。
1-2-1-5. 递归行为和递归行为时间复杂度的估算(P3认识O(NlogN)的排序)

用递归方法找一个数组中的最大值,系统上到底怎么做的?
master工时的使用

master公式
master公式

悬而未决的方法会压倒栈里去

1-2-1-5-1. master公式表达式说明
  • T(N) 母问题的数据量是N:案例为arr的长度N
  • N/b是子问题的规模都是N/b:案例是N/2;子问题数据是等量规模的。
  • a是子问题被调用次数:案例是调用2次
  • O(N^d)除去调用之外剩下的过程时间复杂度:案例是直接使用math函数返回是常数时间复杂度O(1);d=0
  1. public class Code08_GetMax { 
  2. public static int getMax(int[] arr) { 
  3. return process(arr,0,arr.length-1); 
  4. } 
  5.  
  6. private static int process(int[] arr, int L, int R) { //process母问题规模N 
  7. if(L==R){//arr[L...R]范围上只有一个数直接返回 
  8. return arr[L]; 
  9. } 
  10. /* 
  11. * mid=(L+R)/2 中点一般这样计算,但是数组长度太大L+R可能溢出,mid可能算出负值下标 
  12. * 可以写成mid=L+((R-L)/2) 除2可以换成位运算右移一位 
  13. * */ 
  14. int mid=L+((R-L)>>1);//中点 
  15. int leftMax=process(arr,L,mid);//子问题规模N/2 
  16. int rightMzx=process(arr,mid+1,R);//子问题调用次数是2次 
  17. return Math.max(leftMax,rightMzx); 
  18. } 
  19. } 

不符合master公式案例
不符合master公式案例

如果logb^a<d 时间复杂度是O(N^d)如下图手写第一种就是上图master公式书写形式

master公式手写形式
master公式手写形式

1-2-1-5-2. 对数与指数

如果a^x =N(a>0,且a≠1),那么数x叫做以a为底N的对数,记作x=logaN,读作以a为底N的对数,其中a叫做对数的底数,N叫做真数。(上述master公式案例x=1所以常数时间复杂度是O(1))

1-2-1-5-3. MergeSort过程 归并排序时间复杂度O(NlogN)
  1. 分成左右两侧有序的子数组:2T(N/2)阶段
  2. 再顺序合并两个数据得到有序的数组:O(N)阶段

master
T(N)=2T(N/2)+O(N)
公式a=2,b=2,d=1符合loga^b=d时间复杂度是O(NlogN)

本地排局部数据落存有序分片其实就是有序的子数组,子数组后续合一进行归并排序合并不同机器数据。

让其整体有序的过程里用了外排序方法。额外空间复杂度O(N)

1-2-1-5-4. 小和问题(左侧比自己小的数)

小和数找数逻辑
小和数找数逻辑

最终1是小和数两次,2两次,3两次,4一次
最终和是1+1+3+2+2+3+4=16

左右数相等的时候,一定要先拷贝右组的数而且不产生小和。否则就不易知道有组有多少数比这个相等的数大。

逆序对(左边数比右边数大则两个数构成一个逆序对)

所有数据的处理都要考虑漏重乱序

1-2-2. 快速排序

最坏划分partition的值最偏O(N^2),如果划分值是中点就会O(NlogN)

快排3.0和普通快排导致复杂度优化的逻辑差别
快排3.0和普通快排导致复杂度优化的逻辑差别

1-2-2-1. 荷兰国旗问题

荷兰国旗问题
荷兰国旗问题

交换逻辑当要6和5比较比5大左侧i不动,右侧j交换然后左移
交换逻辑当要6和5比较比5大左侧i不动,右侧j交换然后左移

小于区域推着等于区域往右走撞上右侧区域往左走的位置:每次就会确认下被比较的数(默认从右边第一个数做第一个被比较的数叫base num case)的位置!!递归下去就会确认下所有被比较的数也就是所有的数的位置。

快排的空间复杂度o(logN) 最差是o(N)

1-3. 堆,桶排序及排序总结(P4)

1-3-1.

  1. 堆结构就是用数组实现的完全二叉树结构
  2. 完全二叉树中如果每棵子树最大值在顶部就是大根堆:有序
  3. 完全二叉树中如果每棵子树的最小值在顶部就是小根堆:有序
  4. 堆结构的heap Insert与heap ify操作
  5. 堆结构的增大和减少
  6. 优先级队列结构,就是堆结构

数组顺序和二叉树对应位置
数组顺序和二叉树对应位置

插入数据找插入树大根堆的位置heap Insert
插入数据找插入树大根堆的位置heap Insert

  1. //某个数出现在index上,往上继续移动 
  2. public static void heapInsert(int[] arr,int index){ 
  3. while(arr[index]>arr[(index-1)/2]){ 
  4. swap(arr,index,(index-1)/2); 
  5. index=(index-1)/2; 
  6. } 
  7. } 
  8. //某个数在index位置,能否往下移动 
  9. /* 
  10. *从任何位置都可以做heapify;heapSize限制数组大小,能确认左右孩子是否存在,越界不存在 
  11. *1. 找数中的最大值(放到顶部成堆) 
  12. * 2. 剩下的数据调整成大根堆 
  13. * */ 
  14. private static void heapify(int[] arr, int index, int heapSize) { 
  15. int left=index*2+1;//左孩子的下标 
  16. while (left < heapSize) {//下方还有孩子的时候,left越界就没孩子,left小于右孩子下标 
  17. //两个孩子中,谁值大,把下标给largest 
  18. int largest=left+1<heapSize&&arr[left+1]>arr[left]?left+1:left; 
  19. // 父和孩子之间,谁值大,把下标给largest 
  20. largest=arr[largest]>arr[index]?largest:index; 
  21. if(largest==index){ 
  22. break; 
  23. } 
  24. swap(arr,largest,index); 
  25. index=largest; 
  26. left=index*2+1; 
  27. } 
  28. } 

左右孩子树最大值都比自己小或者自己没有左右孩子数就排序完毕成大根堆。

heapify往下调整,heapInsert往上调整数

两个方法的功能
两个方法的功能

为什么时间复杂度都是logN因为无论是插入还是移除后调整成大根堆都是调整树的高度高度和数的数量N的关系就是logN函数

时间复杂度和高度和数的数量关系
时间复杂度和高度和数的数量关系

堆的调整都是高度的调整所以是logN

如果数都存在通过heapify(从右往左往下)调整出一个大根堆
如果数都存在通过heapify(从右往左往下)调整出一个大根堆

满二叉树:最底层节点=N/2,每个节点heapify往下移动0次,但是循环了一次进行了1次操作代价是1

倒数第二层:N/4,代价是2;如下图

复杂度公式得出的过程
复杂度公式得出的过程

如果数不是一个个增加而是都有可以搞成大根堆如下复杂度
如果数不是一个个增加而是都有可以搞成大根堆如下复杂度

1-3-1-1. 几乎有序数组排序:准备k的小根堆时间复杂度o(N*logK)
1-3-1-1-1. 以10为底
  • 当0<n<10 的时候 nlogn<n
  • 当n=10 的时候 nlogn=n
  • 当n>10 的时候 nlogn>n

也就是说log函数的幂>底数时N*logN会>N;时间复杂度偏高。当幂和底数(底数不能是0和1)相同log函数值为1得O(1);

1-3-1-1-2. 手写堆的需求场景
  • 手写堆的场景需求:形成堆的数据需要指定位置的数据进行修改,手写可以以最少代价减少heapify,heapinsert次数;
  • 但是系统的优先级队列不支持,这种调整数据的需求,因为它的代价太高要重新所有数据进行多次的heapify

1-3-2. 比较器(第三天内容)

1-3-2-1. 比较器的使用
  1. 比较器(JAVA)的实质就是重载比较运算符(C++)
  2. 比较器可以很好的应用在特殊标准的排序上
  3. 比较器可以很好的应用在根据特殊标准排序的结构上
1-3-2-2. 排序总结
  • 基于比较排序
  • 不基于比较排序与数据状况有关
1-3-2-2-1. 计数排序

不基于比较排序案例
不基于比较排序案例

1-3-2-3. 基数排序
  • 比如按照进制数据结构状况的数进行排序17变成017,100等进行排序保证数据位数同等级。

桶的排序时间复杂度是O(N)空间复杂度O(M)
桶的排序时间复杂度是O(N)空间复杂度O(M)

桶的排序需要基于样本数据满足桶的划分才能用桶排序。

桶的排序流程
桶的排序流程

  1. package leecode.zuochengyun.dayof7; 
  2.  
  3. /** 
  4. * create-date:2022/5/27 
  5. * author:guojia.ma 
  6. * 不通过比较的排序1。计数排序2.基数排序:此处案例桶排序 
  7. */ 
  8. public class Code02_RadixSort { 
  9. // only for no-neagtive value 
  10. public static void radixSort(int[] arr) { 
  11. if(arr==null||arr.length<2){ 
  12. return; 
  13. } 
  14. radixSort(arr,0,arr.length-1,maxbits(arr)); 
  15. } 
  16. //arr[begin..end]排序 
  17. private static void radixSort(int[] arr, int L, int R, int digit) { 
  18. final int radix=10; 
  19. int i=0,j=0; 
  20. // 有多少个数准备多少个辅助空间 
  21. int[] bucket=new int[R-L+1]; 
  22. for (int d = 0; d <=digit; d++) {//有多少位就每个数字进出桶多少次 
  23. // 10个空间 
  24. // count[0] 当前位(d位)是0的数字有多少个 
  25. // count[1] 当前位(d位)是(0和1)的数字有多少个 
  26. // count[i] 当前位(d位)是(0~i)的数字有多少个 
  27. int[] count=new int[radix];//count[0..9] 
  28.  
  29. for ( i = 0; i < radix; i++) { 
  30. j=getDigit(arr[i],d); 
  31. count[j]++; 
  32. } 
  33. for ( i = 0; i < radix; i++) {//累加和做词频 
  34. count[i]=count[i]+count[i-1]; 
  35. } 
  36. for ( i = R; i >=L ; i--) {//数组从右往左遍历数字出桶 
  37. j=getDigit(arr[i],d ); 
  38. bucket[count[j]-1]=arr[i];//辅助数组 
  39. count[j]--; 
  40. } 
  41. for (i = L,j =0; i<=R;i++,j++) { 
  42. arr[i]=bucket[j];//把bucket出桶的结果数怼回到原数组, 
  43. } 
  44. }//循环其他位进行入桶出桶怼回原数组 
  45. } 
  46.  
  47. private static int getDigit(int x, int d) { 
  48. return ((x/((int)Math.pow(10,d-1)))%10); 
  49. } 
  50.  
  51. private static int maxbits(int[] arr) { 
  52. int max=Integer.MIN_VALUE; 
  53. for (int i = 0; i < arr.length; i++) { 
  54. max=Math.max(max,arr[i]); 
  55. } 
  56. int res=0; 
  57. while (max!=0){ 
  58. res++; 
  59. max/=10;//最大值有多少十进制位 
  60. } 
  61. return res; 
  62. } 
  63.  
  64. } 

1-4. 链表(P5)

1-4-1. 排序算法的稳定性(5-5相等不发生位置相对次序变更)及其汇总

  • 同样值的个体之间,如果不因为排序而改变相对次序,就是这个排序是有稳定性的;否则就没有。
  • 不具备稳定性的排序:选择排序,快速排序,堆排序
  • 具备稳定性的排序:冒泡排序,插入排序,归并排序,一切桶排序思想下的排序

目前:基于比较的排序没有找到时间复杂度O(N*logN);额外空间复杂度O(1)和稳定性的排序二选一的排序。

排序时空和稳定总结
排序时空和稳定总结

1-4-1-1. 常见坑
  1. 归并排序的额外空间度为O(1),有兴趣可以搜“归并排序”内部缓存法=》将导致稳定性消失,不如直接使用堆排序!!
  2. "原地归并排序“的帖子都是垃圾,会让归并排序时间复杂度变成o(N^2),不如直接使用插入排序
  3. 快速排序可以zuo8dao稳定性问题,但是非常难,可以搜“01 stable sort”=》空间复杂度将上升到O(N)不如直接使用归并排序
  4. 有一道题目,是奇数放在数组左边,偶数放在数组右边,要求原始的相对次序不变,碰到这个问题,可以怼面试官。

0-1标准的01 stable sort
0-1标准的01 stable sort

1-4-1-2. 工程上排序改进
  1. 充分利用O(N*logN)和O(N^2)排序各自的优势
  2. 稳定性的考虑

改进案例讲解
改进案例讲解

一般基础类型不考虑稳定性用快排,复杂类型可能要求稳定性用归并排序.

1-4-2. hash表

  • 哈希表在使用层面上可以理解为一种集合结构
  • 如果只有key,没有伴随数据value,可以使用hashSet结构(C++中叫UnOrderedSet)
  • 如果既有key,又有伴随value,可以使用HashMap结构(C++中叫UnOrderedMap)
  • 有无伴随数据是map和set的唯一区别,底层的实际结构是一样的。
  • 使用hash表 增删改查都是时间复杂度都是O(1)但是常数时间级别比较大。
  • 放入hash表的东西,如果是基础类型,内部按值传递,内存占用就是这个东西的大小
  • 放入hash表的东西,如果不是基础类型,内部按照引用传递,内存占用是这个东西内存地址的大小。

有关hash表原理将在提升班hansh函数有关的数据结构一章讲解。

1-4-2-1. 有序表介绍
  • 有序表在使用层面上可以理解为一种集合结构
  • 如果只有key,没有伴随value,可以使用TreeSet结构(C++叫OrderedSet)
  • 如果既有key,又有value,可以使用TreeMap(C++叫OrderedMap)结构
  • 有无伴随数据,是TreeSet和TreeMap的唯一区别,底层实际是一回事。
  • 红黑树,AVL数,size-balance-tree(傻逼树?)和跳表等都属于有序表结构,只是底层具体实现不同。
  • 放入hash表,是基础类型值传递,内存是这个东西的大小(值大小
  • 放入hash表,不是基础类型,必须提供比较器,引用传递,内存是地址的大小
  • 不管什么底层实现,只要是有序表,都有以下固定的基本公共能力和固定的时间复杂度
1-4-2-1-1. 有序表的固定操作
  • void put(key,value):讲一个(k,v)记录加入到表中,获奖k的记录更新成v.
  • v get(k): 根据给定的k,查询v返回
  • void remove(k):移出k的记录
  • boolean containsKey(k):询问是否有关于k的记录
  • K firstKye():返回所有键值的排序结果中,最左(小)的那个
  • K lastKey():返回所有键值的排序结果中,最右(大)的那个
  • K floorKey(k):如果表中存在key返回k,否则返回所有键值的排序结果中,key的前一个。
  • K ceilingKey(k):如果表中存在key返回k,否则返回所有键值的排序结果中,key的后一个。

以上所有操作时间复杂度都是O(logN),N为有序表含有的记录数,有关有序表原理,将在有序表详解一章讲述。涉及原理的题一般都是难题;

1-4-3. 链表

单链表和双链表Node结构
单链表和双链表Node结构

1-4-4. 反转

  1. 题目:分别实现翻转单向链表和反转双向链表的函数
    要求:如果链表长度为N,时间复杂度要求O(N),额外空间复杂度O(1)

如果链表需要换头就要方法带返回值,否则直接void即可。head=f(head).

1-4-4-1. 打印有序链表公共部分
  1. 题目:给定两个有序链表的头指针head1和head2,打印两个链表的公共部分。
    要求:如果两个链表的长度之和为N,时间复杂度要求O(N),额外空间复杂度O(1)
1-4-4-2. 链表解体方法论
  1. 对于笔试,不用太在乎空间复杂度,一切为了时间复杂度
  2. 对于面试,时间复杂度放在第一位,但是一定要找到空间最省的方法
1-4-4-2-1. 额外技巧:
  1. 额外数据机构记录(笔试快速写)(hash表等)
  2. 快慢指针(一定要自己练coding:跨的步子不一样比如快指针走2步慢走1步,快走完了慢走到中间位置(要根据长度是奇数还是偶数定制))
1-4-4-3. 回文结构(笔试:栈结构)

题目:给定一个单链表的头结点head,请判断该链表是否为回文结构。
例子:1-》2-》1,返回true,1->2->2-1返回true,15->6->15 返回true,1-》2->3返回false.
面试要求:如果链表长度为N,时间复杂度达到O(N),额外空间复杂度为O(1):用链表,用几个变量的额外空间(主要考察coding能力)

1-4-4-4. 讲单链表按某值分成左边小,中间等,右边大的形式

题目:给定一个单链表的头节点head,节点的值类型是整型,再给定一个整数privot.实现一个调整链表的函数,讲链表调整为左部分都是值小于privot的节点,中间部分都是值等于privot的节点,有部分都是值大于privot的节点。
进阶:在实现原问题功能基础上增加如下要求
要求1:调整后所有小于privot的节点之间的相对顺序和调整前一样
要求2:调整后所有等于privot的节点之间的相对顺序和调整前一样
要求3:调整后所有大于privot的节点之间的相对顺序和调整前一样
要求4:时间复杂度达到0(N),额外空间复杂度请达到0(1)

案例图解
案例图解

  1. public static Node listPartition2(Node head,int privot){ 
  2. Node sH=null;//small head 
  3. Node sT=null;//small tail 
  4. Node eH=null;//equal head 
  5. Node eT=null;//equal tail 
  6. Node mH=null;//big head 
  7. Node mT=null;//big tail 
  8. Node next=null;//save next node 
  9. //every node distributed to three lists 
  10. while(head!=null){ 
  11. next=head.next; 
  12. head.next=null; 
  13. if(head.value<privot){ 
  14. if(sH==null){ 
  15. sH=head; 
  16. sT=head; 
  17. }else{ 
  18. sT.next=head; 
  19. sT=head; 
  20. } 
  21. }else if(head.value==privot){ 
  22. if(eH==null){ 
  23. eH=head; 
  24. eT=head; 
  25. }else{ 
  26. eT.next=head; 
  27. eT=head; 
  28. } 
  29. }else{ 
  30. if(mH==null){ 
  31. mH=head; 
  32. mT=head; 
  33. }else { 
  34. mT.next=head; 
  35. mT=head; 
  36. } 
  37. } 
  38. head=next; 
  39. } 
  40. //small and equal reconnect 
  41. if(sT!=null){ 
  42. //如果有小于区域 
  43. sT.next=eH; 
  44. eT=eT==null?sT:eT;//下一步,谁去连接大于区域的头,谁变成eT 
  45. } 
  46. //上面的if,不管跑了没有,et 
  47. //all reconnect 
  48. if(eT!=null){//如果小于区域和等于㻃,不是都没有 
  49. eT.next=mH; 
  50. } 
  51. return sH!=null?sH:(eH!=null?eH:mH); 
  52. } 
1-4-4-5. 复制含有随机指针节点的链表

题目和要求
题目和要求

  1. public static class Node{ 
  2. public int value; 
  3. public Node next; 
  4. public Node rand; 
  5. public Node(int data){ 
  6. this.value=data; 
  7. } 
  8. } 
  9. public static Node copyListWithRand1(Node head){ 
  10. HashMap<Node, Node> map = new HashMap<>(); 
  11. Node cur=head; 
  12. while (cur!=null){ 
  13. map.put(cur,new Node(cur.value)); 
  14. cur=cur.next; 
  15. } 
  16. cur=head; 
  17. while (cur!=null){ 
  18. //cur 老 
  19. //map.get(cur)//新 
  20. map.get(cur).next=map.get(cur.next); 
  21. map.get(cur).rand=map.get(cur.rand); 
  22. cur=cur.next; 
  23. } 
  24. return map.get(head); 
  25. } 
1-4-4-6. 单链表相交的一系列问题(单链表最难)

题目:给定两个可能有环也可能无环的单链表,头结点head1和head2.请实现一个函数,如果两个链表相交,请返回相交的第一个节点。如果不相交,返回null
要求:如果两个链表长度和未N,时间复杂度请达到O(N),额外空间复杂度请达到O(1)

  1. /** 
  2. * create-date:2022/6/15 
  3. * author:guojia.ma 
  4. * 单链相交节点 
  5. */ 
  6. public class Code07_FindFirstIntersectNode { 
  7. public static class Node { 
  8. public int value; 
  9. public Node next; 
  10. public Node(int data){ 
  11. this.value=data; 
  12. } 
  13. } 
  14.  
  15. public static Node getIntersectNode(Node head1,Node head2){ 
  16. if(head1==null||head2==null){ 
  17. return null; 
  18. } 
  19. Node loop1=getLoopNode(head1); 
  20. Node loop2=getLoopNode(head2); 
  21. if(loop1==null&&loop2==null){ 
  22. return noLoop(head1,head2);//无环链表 
  23. } 
  24. if(loop1!=null&&loop2!=null){//两个链表都有环:环可以独立,可以同一个环:同一个环也可以是不同入环节点loopN 
  25. return bothLoop(head1,loop1,head2,loop2); 
  26. } 
  27. return null; 
  28. } 
  29. // 两个有环链表,返回第一个相交节点(相对任意一个链表的第一个相交),如果不想交返回null 
  30. private static Node bothLoop(Node head1, Node loop1, Node head2, Node loop2) { 
  31. Node cur1=null; 
  32. Node cur2=null; 
  33. if(loop1==loop2){ 
  34. cur1=head1; 
  35. cur2=head2; 
  36. int n=0; 
  37. while (cur1!=loop1){ 
  38. n++; 
  39. cur1=cur1.next; 
  40. } 
  41. while(cur2!=loop2){ 
  42. n--; 
  43. cur2=cur2.next; 
  44. } 
  45. cur1=n>0?head1:head2; 
  46. cur2=cur1==head1?head2:head1; 
  47. n=Math.abs(n); 
  48. while(n!=0){ 
  49. n--; 
  50. cur1=cur1.next; 
  51. } 
  52. while(cur1!=cur2){ 
  53. cur1=cur1.next; 
  54. cur2=cur2.next; 
  55. } 
  56. return cur1; 
  57. }else{ 
  58. cur1=loop1.next; 
  59. while(cur1!=loop1){ 
  60. if(cur1==loop2){//cur1遇到loop2即第二个链的相交节点 
  61. return loop1; 
  62. } 
  63. cur1=cur1.next; 
  64. } 
  65. return null; 
  66. } 
  67. } 
  68. // 如果两个链表都无环,返回第一个相交节点如果不相交,返回null 
  69. private static Node noLoop(Node head1, Node head2) { 
  70. if(head1==null||head2==null){ 
  71. return null; 
  72. } 
  73. Node cur1 = head1; 
  74. Node cur2 = head2; 
  75. int n=0; 
  76. while (cur1.next!=null){ 
  77. n++; 
  78. cur1 = cur1.next; 
  79. } 
  80. while(cur2.next!=null){ 
  81. n--; 
  82. cur2=cur2.next; 
  83. } 
  84. if(cur1!=cur2){//如果两个链表末尾节点不同就不想交 
  85. return null; 
  86. } 
  87. cur1=n>0?head1:head2;//谁长,谁的头变成cur1 
  88. cur2=cur1==head1?head2:head1;//谁短,谁的头变成cur2 
  89. n=Math.abs(n);//两个链表的长度差值,让长的链表先走n;两个再2一期走1步步走,最终在相交点相碰 
  90. while (n!=0){ 
  91. n--; 
  92. cur1=cur1.next; 
  93. } 
  94. while(cur1!=cur2){ 
  95. cur1=cur1.next; 
  96. cur2=cur2.next; 
  97. } 
  98. return cur1; 
  99. } 
  100. // 找到链表第一个入环节点,如果无环,返回null 
  101.  
  102. private static Node getLoopNode(Node head) { 
  103. if(head==null||head.next==null||head.next.next==null){ 
  104. return null; 
  105. } 
  106. Node n1 = head.next;//n1->slow 指针 
  107. Node n2 = head.next.next;//n2->fast 快指针 
  108. while(n1!=n2){//如果存在环,快慢指针相遇就在环的第一个节点 
  109. if(n2.next==null||n2.next.next==null){ 
  110. return null;//如果快指针提前走到尾2,就不存在环2 
  111. } 
  112. n2=n2.next.next; 
  113. n1=n1.next; 
  114. } 
  115. n2=head;//n2->walk again from head 
  116. while (n1!=n2){ 
  117. n1=n1.next; 
  118. n2=n2.next; 
  119. } 
  120. return n1; 
  121. } 
  122. } 

1-5. 二叉树(P6)

class Node<v>{
  V value;
  Node left;
  Node right;
}
  • 用递归和非递归两种方式实现二叉树的先序,中序,后序2遍历
  • 如何只管的打印一颗二叉树
  • 如何完成二叉树的宽度优先遍历(常见题目:求一颗二叉树的宽度)

1-5-1. 递归序

递归序的描述图
递归序的描述图

递归序代码模型
递归序代码模型

基于递归序可以加工出先中后三种遍历顺序。

1-5-1-1. 递归的先中后遍历

遍历原理
遍历原理

  1. package leecode.zuochengyun.dayof7; 
  2.  
  3. import java.util.Stack; 
  4.  
  5. /** 
  6. * create-date:2022/6/15 
  7. * author:guojia.ma 
  8. * 二叉树的基于递归的先中后遍历 
  9. */ 
  10. public class Code01_PreInPosTraversal { 
  11. public static class Node{ 
  12. public int value; 
  13. public Node left; 
  14. public Node right; 
  15. public Node(int data){ 
  16. this.value=data; 
  17. } 
  18. } 
  19. //先序遍历 
  20. public static void preOrderRecur(Node head){ 
  21. if(head==null){ 
  22. return; 
  23. } 
  24. System.out.print(head.value+" "); 
  25. preOrderRecur(head.left); 
  26. preOrderRecur(head.right); 
  27. } 
  28. //中序遍历 
  29. public static void inOrderRecur(Node head){ 
  30. if(head==null){ 
  31. return; 
  32. } 
  33. inOrderRecur(head.left); 
  34. System.out.print(head.value+" "); 
  35. inOrderRecur(head.right); 
  36. } 
  37.  
  38. //后序遍历 
  39. public static void posOrderRecur(Node head){ 
  40. if(head==null){ 
  41. return; 
  42. } 
  43. posOrderRecur(head.left); 
  44. posOrderRecur(head.right); 
  45. System.out.print(head.value+" "); 
  46. } 
  47. // 非递归先序遍历 
  48. public static void preOrderUnRecur(Node head){ 
  49. System.out.print("pre-order: "); 
  50. if(head!=null){ 
  51. Stack<Node> stack = new Stack<Node>(); 
  52. stack.add(head); 
  53. while(!stack.isEmpty()){ 
  54. head = stack.pop(); 
  55. System.out.print(head.value+" "); 
  56. if(head.right!=null){ 
  57. stack.push(head.right); 
  58. } 
  59. if(head.left!=null){ 
  60. stack.push(head.left); 
  61. } 
  62. } 
  63. } 
  64. System.out.println(); 
  65. } 
  66. } 
  67.  

二叉树的先序遍历就是深度遍历

宽度遍历用队列;从头进,先放左再放右;然后从尾开始依次弹出。

1-5-1-2. 二叉树的相关概念及实现判断
  • 如何判断一颗二叉树是否是搜索二叉树(BST ):左比父小,右比父大,中序遍历升序?
  1. // 判断是否是搜索二叉树BST 
  2. public static int preValue=Integer.MIN_VALUE; 
  3. public static boolean checkBST(Node head){ 
  4. if(head==null){ 
  5. return true; 
  6. } 
  7. boolean isLeftBst=checkBST(head.left); 
  8. if(!isLeftBst){ 
  9. return false; 
  10. } 
  11. if(head.value<=preValue){ 
  12. return false; 
  13. }else { 
  14. preValue=head.value; 
  15. } 
  16.  
  17. return checkBST(head.right); 
  18. } 
  • 如何判断一颗二叉树是完全二叉树:从左到右依次变满?
  1. // 判断是否是完全二叉树CBT:宽度有限遍历 
  2. public static boolean isCBT(Node head){ 
  3. if(head==null){ 
  4. return true; 
  5. } 
  6. LinkedList<Node> queue = new LinkedList<>(); 
  7. // 是否遇到过左右两个孩子不双全的节点 
  8. boolean leaf=false; 
  9. Node l=null; 
  10. Node r=null; 
  11. queue.add(head); 
  12. while(!queue.isEmpty()){ 
  13. head=queue.poll(); 
  14. l=head.left; 
  15. r=head.right; 
  16. if((leaf&&(l!=null||r!=null)) 
  17. ||(l==null&&r!=null)){//有右无左 
  18. return false; 
  19. } 
  20. if(l!=null){ 
  21. queue.add(l); 
  22. } 
  23. if(r!=null){ 
  24. queue.add(r); 
  25. } 
  26. if(l==null||r==null){ 
  27. leaf=true; 
  28. } 
  29. } 
  30. return true; 
  31. } 
  • 如何判断一颗二叉树是否是满二叉树?最大深度L,节点数N满足:N=2^L-1

  • 如何判断一颗二叉树是否是平衡二叉树?(二叉树题目套路):任何一个子树左树和右树的高度差不超过1

  1. package leecode.zuochengyun.dayof7; 
  2.  
  3. /** 
  4. * create-date:2022/6/16 
  5. * author:guojia.ma 
  6. * 平衡二叉树判断 
  7. */ 
  8. public class Code06_IsBalancedTree { 
  9. public static class Node{ 
  10. public int value; 
  11. public Node left; 
  12. public Node right; 
  13. public Node(int data){ 
  14. this.value=data; 
  15. } 
  16. } 
  17.  
  18. public static boolean isFull(Node head){ 
  19. ReturnData allInfo=p(head); 
  20. return (1<<allInfo.height-1)==allInfo.nums; 
  21. } 
  22.  
  23. public static class ReturnData{ 
  24. public int height; 
  25. public int nums; 
  26. public ReturnData(int h,int n){ 
  27. height=h; 
  28. nums=n; 
  29. } 
  30. } 
  31.  
  32. public static ReturnData p(Node x){ 
  33. if(x==null){ 
  34. return new ReturnData(0,0); 
  35. } 
  36. ReturnData leftData=p(x.left); 
  37. ReturnData rightData=p(x.right); 
  38.  
  39. int height=Math.max(leftData.height,rightData.height)+1; 
  40.  
  41. int nums=leftData.nums+rightData.nums+1; 
  42.  
  43. return new ReturnData(height,nums); 
  44.  
  45. } 
  46.  
  47. public static boolean isBalanced(Node head){ 
  48. return process(head).isBalanced; 
  49. } 
  50.  
  51.  
  52. public static class ReturnType{ 
  53. public boolean isBalanced; 
  54. public int height; 
  55. public ReturnType(boolean isB,int hei){ 
  56. isBalanced=isB; 
  57. height=hei; 
  58. } 
  59. } 
  60.  
  61. public static ReturnType process(Node x){ 
  62. if(x==null){//base case 空树 
  63. return new ReturnType(true,0); 
  64. } 
  65. ReturnType leftData=process(x.left); 
  66. ReturnType rightData=process(x.right); 
  67.  
  68. int height=Math.max(leftData.height,rightData.height)+1; 
  69. boolean isBalanced=leftData.isBalanced && rightData.isBalanced && Math.abs(leftData.height- rightData.height)<2; 
  70. return new ReturnType(isBalanced,height); 
  71. } 
  72.  
  73. /* public static class Info{ 
  74. public boolean isBST; 
  75.  
  76. }*/ 
  77.  
  78.  
  79. } 
  80.  
1-5-1-2-1. 二叉树递归套路
  1. 列可能性,左树需要获取多少信息,右树性需要什么信息:比如平衡二叉树就要获取左右两个树是否平?高度多少?递归返回值就是这个信息数据class

所有的树型的DP(动态规划)都是按照这个套路进行coding解决。

1-5-2. 给定两个二叉树的节点node1和node2,找到他们的最低公共祖先节点(网上最早汇聚的点 )

  1. public static Node lowestAncestor(Node head,Node o1,Node o2){ 
  2. if(head==null ||head==o1||head==o2){//base case 
  3. return head; 
  4. } 
  5.  
  6. Node left = lowestAncestor(head.left, o1, o2); 
  7. Node right = lowestAncestor(head.right, o1, o2); 
  8. // 对于情况2 
  9. if(left!=null&&right!=null){ 
  10. return head; 
  11. } 
  12. //对于情况1 两个树,并不都有返回值;一个树既没有o1,o2一定返回空 
  13. return left!=null?left:right; 
  14. } 

最低公共祖先可能性情况
最低公共祖先可能性情况

1-5-2-1. 后继节点(中序遍历中下一个节点)

在二叉树中找到一个几点的后继几点
题目:现在有一种新的二叉树节点类型如下:

pubic class Node{
    public int value;
    public Node left;
    public Node right;
    public Node parent;
    public Node(int val){
       value=val;
    }
}

该结构比普通二叉树节点结构多了一个指向父节点的parent指针。假设有一颗Node类型的节点组成的二叉树,树2中每个节点的parent指针都正确地指向自己的父节点,头结点的parent指向null.
只给一个在二叉树中某个节点node,请实现返回node的后继节点的函数。
在二叉树的中序遍历序列中,node的下一个节点叫做node的后继节点。

后继节点的可能性
后继节点的可能性

  1. public static Node getSuccessorNode(Node node){ 
  2. if(node==null){ 
  3. return node; 
  4. } 
  5. if(node.right!=null){//情况1 
  6. return getLeftMost(node.right); 
  7. }else{//情况2 无右子树 
  8. Node parent = node.parent; 
  9. while (parent!=null&&parent.left!=node){//情况3 当前节点是其父节点右孩子 
  10. node=parent; 
  11. parent=node.parent; 
  12. } 
  13. return parent; 
  14. } 
  15. } 
  16.  
  17. private static Node getLeftMost(Node node) { 
  18. if(node==null){ 
  19. return node; 
  20. } 
  21. while (node.left!=null){ 
  22. node=node.left; 
  23. } 
  24.  
  25. return node; 
  26. } 
1-5-2-2. 二叉树的序列化和反序列化

就是内存里的一颗树如何变成字符串形式,又如何从字符串变成内存里的树?
如何判断一颗二叉树是不是另一颗二叉树的子树?

  1. // 以head为头的树,请序列化成字符串返回//以下递归顺序是先序遍历及序列化 
  2. public static String serialByPre(Node head){ 
  3. if(head==null){ 
  4. return "#_"; 
  5. } 
  6. String res=head.value+"_"; 
  7. res+=serialByPre(head.left); 
  8. res+=serialByPre(head.right); 
  9. return res; 
  10. } 
  11. // 反序列化 
  12. public static Node reconByPreString(String preStr){ 
  13. String[] values = preStr.split("_"); 
  14. Queue<String> queue = new LinkedList<>(); 
  15. for (int i = 0; i !=values.length; i++) { 
  16. queue.add(values[i]); 
  17. } 
  18. return reconPreOrder(queue); 
  19. } 
  20.  
  21. public static Node reconPreOrder(Queue<String> queue) { 
  22. String value=queue.poll(); 
  23. if(value.equals("#")){ 
  24. return null; 
  25. } 
  26. Node head = new Node(Integer.valueOf(value)); 
  27. head.left = reconPreOrder(queue); 
  28. head.right = reconPreOrder(queue); 
  29. return head; 
  30. } 
1-5-2-3. 微软折纸题

图解折纸空间N
图解折纸空间N

  1. public static void printAllFolds(int N) { 
  2. printProcess(1,N,true); 
  3. } 
  4. /* 
  5. * 递归过程,来到了某一个节点 
  6. * i是节点的层数,N是一共的层数,down==true 凹,down==false 凸 
  7. * */ 
  8. public static void printProcess(int i, int N, boolean down) { 
  9. if(i>N){ 
  10. return; 
  11. } 
  12. printProcess(i+1,N,true); 
  13. System.out.println(down?"凹":"凸"); 
  14. printProcess(i+1,N,false); 
  15. } 
  16.  
  17. public static void main(String[] args) { 
  18. int N=3; 
  19. printAllFolds(3); 
  20. } 

1-6. 图(P8)

1-6-1. 图的存储方式

  1. 邻接表
  2. 邻接矩阵

如何表达图?生成图?

邻接表图解:以点考虑
邻接表图解:以点考虑

邻接矩阵图解:以边考虑
邻接矩阵图解:以边考虑

表达图的结构比较多,算法coding就要变,但是算法还是原来的算法。

  1. package leecode.zuochengyun.dayof7; 
  2.  
  3. import java.util.HashMap; 
  4. import java.util.HashSet; 
  5.  
  6. /** 
  7. * create-date:2022/6/17 
  8. * author:guojia.ma 
  9. * 基础班:图 
  10. */ 
  11. public class Graph { 
  12. public HashMap<Integer,Node> nodes; 
  13. public HashSet<Edge> edges; 
  14. public Graph(){ 
  15. nodes=new HashMap<>(); 
  16. edges=new HashSet<>(); 
  17. } 
  18. } 
  19.  
  20. package leecode.zuochengyun.dayof7; 
  21.  
  22. import java.util.ArrayList; 
  23.  
  24. /** 
  25. * create-date:2022/6/17 
  26. * author:guojia.ma 
  27. * 图的点 
  28. */ 
  29. public class Node { 
  30. public int value; 
  31. public int in; 
  32. public int out; 
  33. public ArrayList<Node> nexts; 
  34. public ArrayList<Edge> edges;// 边从出看所属 
  35. public Node(int value){ 
  36. this.value=value; 
  37. in=0; 
  38. out=0; 
  39. nexts=new ArrayList<>(); 
  40. edges=new ArrayList<>(); 
  41. } 
  42. } 
  43.  
  44.  
  45. package leecode.zuochengyun.dayof7; 
  46.  
  47. /** 
  48. * create-date:2022/6/17 
  49. * author:guojia.ma 
  50. * 图的边 
  51. */ 
  52. public class Edge { 
  53. public int weight; 
  54. public Node from; 
  55. public Node to; 
  56. public Edge(int weight,Node from,Node to){ 
  57. this.weight=weight; 
  58. this.from=from; 
  59. this.to=to; 
  60. } 
  61. } 
  62.  
  63.  
  64.  
  65. package leecode.zuochengyun.dayof7; 
  66.  
  67. /** 
  68. * create-date:2022/6/17 
  69. * author:guojia.ma 
  70. * 把数据转化成图结构 
  71. */ 
  72. public class GraphGenerator { 
  73. /* 
  74. * matrix所有的边 
  75. * N*3的矩阵 
  76. * 【weigbht,from节点上面的值,to节点上面的值】 
  77. * */ 
  78.  
  79. public static Graph createGraph(Integer[][] matrix){ 
  80. Graph graph=new Graph(); 
  81. for (int i = 0; i < matrix.length; i++) { 
  82. Integer from = matrix[i][0]; 
  83. Integer to = matrix[i][1]; 
  84. Integer weight = matrix[i][2]; 
  85. if(!graph.nodes.containsKey(from)){ 
  86. graph.nodes.put(from,new Node(from)); 
  87. } 
  88. if(!graph.nodes.containsKey(to)){ 
  89. graph.nodes.put(to,new Node(to)); 
  90. } 
  91. Node fromNode = graph.nodes.get(from); 
  92. Node toNode = graph.nodes.get(to); 
  93. Edge newEdge = new Edge(weight, fromNode, toNode); 
  94. fromNode.nexts.add(toNode); 
  95. fromNode.out++; 
  96. toNode.in++; 
  97. fromNode.edges.add(newEdge); 
  98. graph.edges.add(newEdge); 
  99. } 
  100. return graph; 
  101. } 
  102.  
  103. } 

1-6-2. 图的宽度和广度优先遍历

1-6-2-1. 宽度优先
  1. 利用队列实现
  2. 从源节点开始依次按照宽度进队列,然后弹出
  3. 每弹出一个点,把该节点所有没有进过队列的邻接点放入队列
  4. 直到队列变空
  1. // 从node出发,进行宽度优先遍历 
  2. public static void bfs(Node node){ 
  3. if(node==null){ 
  4. return; 
  5. } 
  6. Queue<Node> queue = new LinkedList<>(); 
  7. HashSet<Node> set=new HashSet<>(); 
  8. queue.add(node); 
  9. set.add(node); 
  10. while (!queue.isEmpty()){ 
  11. Node cur = queue.peek(); 
  12. System.out.println(cur.value); 
  13. for (Node next:cur.nexts 
  14. ) { 
  15. if(!set.contains(next)){ 
  16. set.add(next); 
  17. queue.add(next); 
  18. } 
  19. } 
  20. } 
  21. } 
1-6-2-2. 广度(深度)优先
  1. 利用栈实现
  2. 从源节点开始把节点按照深度放入栈,然后弹出
  3. 每弹出一个点,把该节点下一个没有进过栈的邻接点放入栈
  4. 直到栈变空。
  1. public static void dfs(Node node){ 
  2. if(node==null){ 
  3. return; 
  4. } 
  5. Stack<Node> stack = new Stack<>(); 
  6. HashSet<Node> set = new HashSet<>(); 
  7. stack.add(node);//当前节点入栈,入set 
  8. set.add(node); 
  9. System.out.println(node.value); 
  10. while(!stack.isEmpty()){ 
  11. Node cur=stack.pop();//当前节点出栈 
  12. for (Node next:cur.nexts 
  13. ) { 
  14. if(!set.contains(next)){ 
  15. stack.push(cur);//当前节点入栈 
  16. stack.push(next);//当前节点邻居节点入栈 
  17. set.add(next);//注册邻居节点(没有遍历过的遍历并注册,已经遍历过的就注册过,只不过从新放入栈中,后面直接while弹出来即可。) 
  18. System.out.println(next.value); 
  19. break; 
  20. } 
  21. } 
  22. } 
  23. } 

1-6-3. 拓扑排序算法

使用范围:要求有向图,且入度为0的节点,且没有环。

  1. // directed grouph and no loop 
  2. public static List<Node> sortedTopology(Graph graph){ 
  3. // key:某一个node 
  4. // value:剩余的入度 
  5. HashMap<Node,Integer> inMap=new HashMap<>(); 
  6. // 入度为0的点,才能进入这个队列 
  7. Queue<Node> zeroInQueue=new LinkedList<>(); 
  8. for (Node node:graph.nodes.values() 
  9. ) { 
  10. inMap.put(node,node.in); 
  11. if(node.in==0){ 
  12. zeroInQueue.add(node); 
  13. } 
  14. } 
  15. // 拓扑排序的结果,一次加入result 
  16. List<Node> result=new ArrayList<>(); 
  17. while(!zeroInQueue.isEmpty()){ 
  18. Node cur = zeroInQueue.poll(); 
  19. result.add(cur); 
  20. for (Node next:cur.nexts 
  21. ) { 
  22. inMap.put(next,inMap.get(next)-1);//擦除上个入度为0的后续节点的影响 
  23. if(inMap.get(next)==0){ 
  24. zeroInQueue.add(next);//把入度为0的放到result里 
  25. } 
  26. } 
  27. } 
  28. return result; 
  29. } 

1-6-4. 最小生成树:权值和最小的边保留

  1. // Union-Find Set 
  2. public static class UnionFind { 
  3. // key 某一个节点,value key节点往上的节点 
  4. private HashMap<Node,Node> fatherMap; 
  5. // key 某一个集合的代表节点,value key所在集合的节点个数 
  6. private HashMap<Node,Integer> sizeMap; 
  7. public UnionFind(){ 
  8. fatherMap=new HashMap<Node,Node>(); 
  9. sizeMap=new HashMap<Node,Integer>(); 
  10. } 
  11. public void makeSets(Collection<Node> nodes){ 
  12. fatherMap.clear(); 
  13. sizeMap.clear(); 
  14. for (Node node:nodes 
  15. ) { 
  16. fatherMap.put(node,node); 
  17. sizeMap.put(node,1); 
  18. } 
  19. } 
  20.  
  21. private Node findFather(Node n){ 
  22. Stack<Node> path=new Stack<>(); 
  23. while(n!=fatherMap.get(n)){ 
  24. path.add(n); 
  25. n=fatherMap.get(n); 
  26. } 
  27. while (!path.isEmpty()){ 
  28. fatherMap.put(path.pop(),n); 
  29. } 
  30. return n; 
  31. } 
  32.  
  33. public boolean isSameSet(Node a,Node b){ 
  34. return findFather(a)==findFather(b); 
  35. } 
  36.  
  37. public void union(Node a,Node b) { 
  38. if (a == null || b == null) { 
  39. return; 
  40. } 
  41. Node aDai = findFather(a); 
  42. Node bDai = findFather(b); 
  43. if (aDai != bDai) { 
  44. int aSetSize = sizeMap.get(aDai); 
  45. int bSetSize = sizeMap.get(bDai); 
  46. if (aSetSize <= bSetSize) { 
  47. fatherMap.put(aDai, bDai); 
  48. sizeMap.put(bDai, aSetSize + bSetSize); 
  49. sizeMap.remove(aDai); 
  50. } else { 
  51. fatherMap.put(bDai, aDai); 
  52. sizeMap.put(aDai, aSetSize + bSetSize); 
  53. sizeMap.remove(bDai); 
  54. } 
  55. } 
  56. } 
  57. } 
  58.  
  59. public static class EdgeComparator implements Comparator<Edge> { 
  60.  
  61. @Override 
  62. public int compare(Edge o1, Edge o2) { 
  63. return o1.weight-o2.weight; 
  64. } 
  65. } 
1-6-4-1. kruskal算法(K算法) :并集查

以边的角度出发,边排序,一个个加并判断是否成环,成环就不加;判断是否成环就要靠一种数据结构
使用范围:要求无向图;

  1. public static Set<Edge> kruskalMST(Graph graph){ 
  2. UnionFind unionFind = new UnionFind(); 
  3. unionFind.makeSets(graph.nodes.values()); 
  4. PriorityQueue<Edge> priorityQueue = new PriorityQueue<>(new EdgeComparator()); 
  5. for (Edge edge:graph.edges 
  6. ) {//M条边 
  7. priorityQueue.add(edge);//O(logM) 
  8. } 
  9. Set<Edge> result=new HashSet<>(); 
  10. while(!priorityQueue.isEmpty()){ 
  11. Edge edge = priorityQueue.poll();//M条边 
  12. if(!unionFind.isSameSet(edge.from,edge.to)){//o(1) 
  13. result.add(edge); 
  14. unionFind.union(edge.from,edge.to); 
  15. } 
  16. } 
  17. return result; 
  18. } 
1-6-4-2. prim算法(P算法):从点角度考虑
  1. public static class EdgeComaprator implements Comparator<Edge>{ 
  2.  
  3. @Override 
  4. public int compare(Edge o1, Edge o2) { 
  5. return o1.weight-o2.weight; 
  6. } 
  7. } 
  8.  
  9. public static Set<Edge> primMST(Graph graph){ 
  10. // 解锁的边2进入小根堆:按边大小的顺序放边=》放所有解锁的边。 
  11. PriorityQueue<Edge> priorityQueue=new PriorityQueue<>(new EdgeComaprator()); 
  12. HashSet<Node> set=new HashSet<>(); 
  13. Set<Edge> resul=new HashSet<>();//依次挑选的最小边在result里:不在set的点就是新的点 
  14. for (Node node:graph.nodes.values() 
  15. ) {//随便挑一个点 
  16. // node是开始点 
  17. if(!set.contains(node)){ 
  18. set.add(node); 
  19. for (Edge edge: node.edges 
  20. ) {//由一个点解锁所有相连的边 
  21. priorityQueue.add(edge); 
  22. } 
  23. while(!priorityQueue.isEmpty()){ 
  24. Edge edge = priorityQueue.poll();//弹出解锁的边中,最小的边 
  25. Node toNode = edge.to;//可能的一个新的点 
  26. if(!set.contains(toNode)){//不含有的时候,就是新的点 
  27. set.add(toNode); 
  28. resul.add(edge); 
  29. for (Edge nextEdge: toNode.edges 
  30. ) { 
  31. priorityQueue.add(nextEdge);//可能一条边会被重复方队列,不影响最后结论 
  32. } 
  33. } 
  34. } 
  35. } 
  36.  
  37. } 
  38. return resul; 
  39.  
  40. } 

1-6-5. Di jkstra算法(单元最短路径算法)

  • 堆的改写特征,给堆一个,堆吐出一个;不需要再改堆的值;系统能够实现改写,但是是全表扫描代价比较高,最好手动改写,通过向上向下手动调整,可以减少调整的代价。
    适用范围:没有权值为负数的环。
  1. public static HashMap<Node,Integer> dijkstral(Node head){ 
  2. // 从head触发到所有点的最小距离 
  3. // key: 从head出发到达key 
  4. // value: 从head出发到达可以的最小距离 
  5. // 如果在表中,没有T的记录,含义是从head出发到T这个点的距离为正无穷 
  6. HashMap<Node,Integer> distanceMap=new HashMap<>(); 
  7. distanceMap.put(head,0); 
  8. // 已经求过距离的点,存在selectedNodes中,以后再也不碰,锁死 
  9. HashSet<Node> selectedNodes=new HashSet<>(); 
  10. Node minNode= getMinDistanceAndUnselectedNode(distanceMap,selectedNodes); 
  11. while (minNode!=null){ 
  12. int distance=distanceMap.get(minNode); 
  13. for (Edge edge:minNode.edges 
  14. ) { 
  15. Node toNode=edge.to; 
  16. if(!distanceMap.containsKey(toNode)){ 
  17. distanceMap.put(toNode,distance+edge.weight); 
  18. } 
  19. distanceMap.put(edge.to,Math.min(distanceMap.get(toNode),distance+edge.weight));//到达key最小的距离记录 
  20. } 
  21. selectedNodes.add(minNode);//选过的点 
  22. minNode=getMinDistanceAndUnselectedNode(distanceMap,selectedNodes); 
  23. } 
  24. return distanceMap; 
  25. } 
  26. //找出map中最小距离的kv,但是key不能是已经选过的 
  27. public static Node getMinDistanceAndUnselectedNode(HashMap<Node, Integer> distanceMap, HashSet<Node> touchedNodes) { 
  28. Node minNode=null; 
  29. int minDistance=Integer.MAX_VALUE; 
  30. for (Map.Entry<Node,Integer> entry:distanceMap.entrySet() 
  31. ) { 
  32. Node node=entry.getKey(); 
  33. int distance=entry.getValue(); 
  34. if(!touchedNodes.contains(node)&&distance<minDistance){ 
  35. minNode=node; 
  36. minDistance=distance; 
  37. } 
  38. } 
  39. return minNode; 
  40. } 

1-7. 前缀树(标题P9第8章暴力递归):实际是第7章:前缀树和贪心算法;内容顺序有一章节延后

1-7-1. 前缀树

何为前缀树?如何生成前缀树?
例子:
一个字符串类型的数组arr1,另一个字符串类型的数字arr2.arr2中有哪些字符,是arr1中出现的?请打印。arr2中有哪些字符,是作为arr1中某个字符串前缀出现的?请打印。请打印arr2中出现次数最大的前缀。

  1. public static class TrieNode{ 
  2. public int pass; 
  3. public int end; 
  4. public TrieNode[] nexts;//HashMap<Char,Node> nexts; 
  5. public TrieNode(){ 
  6. pass=0; 
  7. end=0; 
  8. // nexts[0]==null 没有走向‘a’的路 
  9. // nexts[0]!=null 有走向‘a’的路 
  10. //... 
  11. //nexts[25]!=null 有走向‘z’的路 
  12. nexts=new TrieNode[26]; 
  13. } 
  14. } 
  15.  
  16. public static class Trie{ 
  17. private TrieNode root; 
  18. public Trie(){ 
  19. root=new TrieNode(); 
  20. } 
  21. public void insert(String word){ 
  22. if(word==null){ 
  23. return; 
  24. } 
  25. char[] chs=word.toCharArray(); 
  26. TrieNode node=root; 
  27. node.pass++; 
  28. int index=0; 
  29. for (int i = 0; i < chs.length; i++) {//从左往右遍历字符 
  30. index=chs[i]-'a';//由字符,对应成走向哪条路 
  31. if(node.nexts[index]==null){ 
  32. node.nexts[index]=new TrieNode(); 
  33. } 
  34. node=node.nexts[index]; 
  35. node.pass++; 
  36. } 
  37. node.end++; 
  38. } 
  39. public void delete(String word){ 
  40. if(search(word)!=0){//确定树中确实加入过word,才删除 
  41. char[] chs=word.toCharArray(); 
  42. TrieNode node=root; 
  43. node.pass--; 
  44. int index=0; 
  45. for (int i = 0; i < chs.length; i++) { 
  46. index=chs[i]-'a'; 
  47. if(--node.nexts[index].pass==0){ 
  48. // JAVA C++要遍历到底去析构 
  49. node.nexts[index]=null;//JAVA=null就是jvm垃圾回收析构了,C++需要一个个遍历处理 
  50. // ... 
  51. return; 
  52. } 
  53. node=node.nexts[index]; 
  54. } 
  55. node.end--; 
  56. } 
  57. } 
  58. // word这个单词之前加入过几次 
  59. public int search(String word){ 
  60. if(word==null){ 
  61. return 0; 
  62. } 
  63. char[] chs=word.toCharArray(); 
  64. TrieNode node=root; 
  65. int index=0; 
  66. for (int i = 0; i < chs.length; i++) { 
  67. index=chs[i]-'a'; 
  68. if(node.nexts[index]==null){ 
  69. return 0; 
  70. } 
  71. node=node.nexts[index]; 
  72. } 
  73. return node.end; 
  74. } 
  75.  
  76. // 所有加入的字符串中,有几个是pre这个字符串作为前缀的 
  77. public int prefixNumber(String pre){ 
  78. if(pre==null){ 
  79. return 0; 
  80. } 
  81. char[] chs = pre.toCharArray(); 
  82. TrieNode node=root; 
  83. int index=0; 
  84. for (int i = 0; i < chs.length; i++) { 
  85. index=chs[i]-'a'; 
  86. if(node.nexts[index]==null){ 
  87. return 0; 
  88. } 
  89. node=node.nexts[index]; 
  90. } 
  91. return node.pass; 
  92. } 
  93. } 

1-7-2. 贪心算法

在某一个标准下,优先考虑最满足标准的样本,最后考虑最不满足标准的样本,最终得到一个答案的算法,叫做贪心算法。
也就是说,不从整体最优上加以考虑,所作出的是在某种意义上的局部最优解。
局部最优-?->整体最优。没到题局部最优到整体最优的证明都不同。

1-7-2-1. 题目:会议问题

一些项目要占用一个会议室宣讲,会议室不能同时容纳两个项目的宣讲。给你每一个项目开始的时间和结束的时间(给你一个数组,里面是一个个具体的项目),你来安排宣讲的日程,要求会议室进行的宣讲场次最多。返回这个最多的宣讲场次。
解体思路:哪个会议结束时间早,最先安排,不能安排的会议删掉。

  1. public static class Program{ 
  2. public int start; 
  3. public int end; 
  4. public Program(int start,int end){ 
  5. this.start=start; 
  6. this.end=end; 
  7. } 
  8. } 
  9.  
  10. public static class ProgramComparator implements Comparator<Program> { 
  11.  
  12. @Override 
  13. public int compare(Program o1, Program o2) { 
  14. return o1.end-o2.end; 
  15. } 
  16. } 
  17.  
  18. public static int bestArrange(Program[] programs,int timePoint){ 
  19. Arrays.sort(programs,new ProgramComparator()); 
  20. int result=0; 
  21. //依次遍历所有会议 
  22. for (int i = 0; i < programs.length; i++) { 
  23. if(timePoint<=programs[i].start){ 
  24. result++; 
  25. timePoint=programs[i].end; 
  26. } 
  27. } 
  28. return result; 
  29. } 
1-7-2-1-1. 贪心算法在笔试时的解题思路(对数器证明贪心算法局部最优-》整体最优的证明)
  1. 实现一个不依靠贪心策略的解法X,可以用最暴力的尝试
  2. 脑补出贪心策略A,贪心策略B,贪心策略C。。。
  3. 用解法X和对数期,取验证每一个贪心策略,用实验的方式得知哪个贪心策略正确
  4. 不要取纠结贪心策略的证明(可以举反例证明某一种贪心错误)
1-7-2-2. 题目:字典顺序最小
  1. public static class MyComparator implements Comparator<String>{ 
  2.  
  3. @Override 
  4. public int compare(String a, String b) {//比较策略(有传递性)就是贪心策略,需证明这个策略有效 
  5. return (a+b).compareTo(b+a);//前一个字典数更低返回负数,否则返回正数 
  6. } 
  7. } 
  8. /* 
  9. *传递性的数据比较策略就是正确的贪心策略的证明就是以下满足:=》前后结果传递性满足 
  10. * a.b<=b.a 
  11. * b.c<=c.b 
  12. * =>a.c<=c.a 
  13. * 最终得到数学函数公式: 
  14. */ 
  15.  
  16. public static String lowestString(String[] strs){ 
  17. if(strs==null||strs.length==0){ 
  18. return ""; 
  19. } 
  20. Arrays.sort(strs,new MyComparator()); 
  21. String res=""; 
  22. for (int i = 0; i < strs.length; i++) { 
  23. res+=strs[i]; 
  24. } 
  25. return res; 
  26. } 

传递性的数据比较策略就是正确的贪心策略的证明就是以下满足:=》前后结果传递性满足

证明比较策略的传递性图解:

比较策略传递性图解
比较策略传递性图解

贪心策略在实现时,经常用到的技巧:

  1. 根据某标准建立一个比较器来排序
  2. 根据某标准建立一个比较器来组成堆
1-7-2-3. 题目六:切金条(哈夫曼编码树)

一块金条长度切成两半,是需要花费和长度数值一样的铜板的。比如长度为20的jintiao9,不管启程长度多大的两半,都要花费20个铜板。
一群人想整分整块金条,怎么分最省铜板?
例如,给定数组{10,20,30},代表一共三个人,整块金条长度为10+20+30=60.金条要分成10,20,30三个部分,如果把长度为60的金条分成10和50,花费是60;再把长度50的金条分成20和30,花费50个铜板,一共花费110个铜板。
但是如果先把长度60的金条分成30和30,花费60,再把30的金条分成10和20,花费30,总共90个铜板。
输入一个数组,返回分割的最小代价。

  1. public static int lessMoney(int[] arr){ 
  2. PriorityQueue<Integer> pQ=new PriorityQueue<>();//小根堆 
  3. for (int i = 0; i < arr.length; i++) { 
  4. pQ.add(arr[i]); 
  5. } 
  6. int sum=0; 
  7. int cur=0; 
  8. while(pQ.size()>1){ 
  9. cur=pQ.poll()+pQ.poll();//每次弹两个 
  10. sum+=cur;//结合一个 
  11. pQ.add(cur);//放入堆里就是哈夫曼编码的树 
  12. } 
  13. return sum; 
  14. } 
  15.  
  16. public static class MinheapComparator implements Comparator<Integer>{ 
  17.  
  18. @Override 
  19. public int compare(Integer o1, Integer o2) { 
  20. return o1-o2;//<0 o1<o2负数 
  21. } 
  22. } 

贪心策略:笔试概率大,考coding,一般5道题的最后一个;但是面试少,因为没有办法考coding,证明起来又比较难。

1-7-2-4. 题目八
  • 贪心策略没有区分度(策略选对就对了,没有所谓的coding能力),如果是为了淘汰率可以出。
    输入:
    正数数组costs
    正数数组profits
    正数k,m
    含义:
    costs[i]标识i号项目的花费,profits[i] 标识i号项目在扣除花费之后还能挣到的钱(利润)
    k标识你只能串行的最多做k个项目,m标识你初始的资金。
    说明:你每做完一个项目,马上获得的收益,可以支持你去做下一个项目。
    输出:你最后获得的最大钱数。

解法图解
解法图解

  1. public static class Node{ 
  2. public int p; 
  3. public int c; 
  4. public Node(int p,int c){ 
  5. this.p=p; 
  6. this.c=c; 
  7. } 
  8. } 
  9.  
  10. public static class MinCostComparator implements Comparator<Node>{ 
  11.  
  12. @Override 
  13. public int compare(Node o1, Node o2) { 
  14. return o1.c-o2.c; 
  15. } 
  16. } 
  17.  
  18. public static class MaxProfitComparator implements Comparator<Node>{ 
  19.  
  20. @Override 
  21. public int compare(Node o1, Node o2) { 
  22. return o1.p-o2.p; 
  23. } 
  24. } 
  25.  
  26. public static int findMaximizedCaptial(int k,int W,int[] Profits,int[] Captial){ 
  27. PriorityQueue<Node> minCostQ=new PriorityQueue<>(new MinCostComparator()); 
  28. PriorityQueue<Node> maxProfitQ=new PriorityQueue<>(new MaxProfitComparator()); 
  29. // 所有项目扔到被锁池中,花费组织的小根堆 
  30. for (int i = 0; i < Profits.length; i++) { 
  31. minCostQ.add(new Node(Profits[i],Captial[i])); 
  32. } 
  33. for (int i = 0; i < k; i++) {//进行K轮 
  34. // 能力所及的项目全解锁 
  35. while(!minCostQ.isEmpty()&&minCostQ.peek().c<=W){ 
  36. maxProfitQ.add(minCostQ.poll()); 
  37. } 
  38. if(maxProfitQ.isEmpty()){ 
  39. return W; 
  40. } 
  41. W+=maxProfitQ.poll().p; 
  42. } 
  43. return W; 
  44. } 

1-8. 堆问题 题目:一个数据流中,随时取得中位数

图解解题过程
图解解题过程

1-9. 暴力递归

1-9-1. 题目 N皇后问题

N皇后问题是指在N*N的期盼上要摆N个皇后,要求任何两个皇后不同行,不同列,也不再同一条斜线上。
给定一个整数n,返回n皇后的摆法有多少种。
n=1,返回1
n=2或3,2皇后和3皇后问题无论怎么摆都不行,返回0
n=8,返回92.

  1. /*优化常数项:2进制的树只使用位信息不使用树的值*/ 
  2. // 请不要超过32皇后问题,位运算最好不要超过32位所以限制32,否则类型换成long 
  3. public static int num2(int n){ 
  4. if(n<1||n>32){ 
  5. return 0; 
  6. } 
  7. int limit=n==32?-1:(1<<n)-1; 
  8. return process2(limit,0,0,0); 
  9. } 
  10. /* 
  11. * colLim 列的限制,1的位置不能放皇后,0的位置可以 
  12. * leftDiaLim 左斜线的限制,1的位置不能方皇后,0的位置可以:通过左位移一位 
  13. * rightDiaLim 右斜线的限制,1的位置不能方皇后,0的位置可以:通过右位移一位 
  14. * */ 
  15. public static int process2(int limit, int colLim, int leftDiaLim, int rightDiaLim) { 
  16. if(colLim==limit){//base case n个皇后而且都合法 
  17. return 1; 
  18. } 
  19. int pos=0; 
  20. int mostRightOne=0; 
  21. pos=limit&(~(colLim|leftDiaLim|rightDiaLim));//三个或后,位上是1的不能放皇后;取反:1可以放皇后0不可以放;取与(&)把左侧位截掉 
  22. int res=0; 
  23. while (pos!=0){ 
  24. mostRightOne=pos&(~pos+1);//最右侧的1提取出来 
  25. pos=pos-mostRightOne; 
  26. res+=process2(limit,colLim|mostRightOne,(leftDiaLim|mostRightOne)<<1,(rightDiaLim|mostRightOne)>>1); 
  27. } 
  28. return res; 
  29. } 

1-10. 补充视频

1-10-1. Dijkstra算法优化改进

1-10-2. 暴力递归

暴力递归就是尝试,只要按照经验选择局部尝试得到结果

  1. 把问题转化为规模缩小了的同类问题的子问题
  2. 有明确的不需要继续进行递归的条件(base case)
  3. 有当得到了子问题结果之后的决策过程
  4. 不记录每一个子问题的解

尝试是动态规划的基础。(将在提升班讲解),试法出来后可以搞动态规划。

1-10-2-1. 汉诺塔问题

打印N层汉诺塔从最左边移动到最右边的过程,最小步数

  1. public static void hanoi(int n){ 
  2. if(n>0){ 
  3. func(n,"左","右","中"); 
  4. } 
  5. } 
  6.  
  7. private static void func(int i, String start, String end, String other) { 
  8. if(i==1){//base case 
  9. System.out.println("Move 1 from"+start+" to "+end); 
  10. }else{ 
  11. func(i-1,start,other,end);//只要局部是对的即可,不要想全局 
  12. System.out.println("Move "+i+" from "+start+" to "+end); 
  13. func(i-1,other,end,start); 
  14. } 
  15. } 
1-10-2-2. 打印字符串的全部子序列,包括空串(就是所有子集)
  1. public static void printAllSubsquences(String str){ 
  2. char[] chs = str.toCharArray(); 
  3. process(chs,0); 
  4. } 
  5. // 当前来到i位置,要和不要,走两条路 
  6. // 之前的选择,所形成的的结果,是string 
  7. private static void process(char[] str, int i) { 
  8. if(i==str.length){ 
  9. System.out.println(String.valueOf(str));//复用str空间,时间复杂度与function一样 
  10. return; 
  11. } 
  12. process(str,i+1); 
  13. char tmp=str[i]; 
  14. str[i]=0; 
  15. process(str,i+1); 
  16. str[i]=tmp; 
  17. } 
1-10-2-3. 打印字符串的全部排列(不要出现重复排列) 排列组合问题
  1. public static ArrayList<String> Permutation(String str){ 
  2. ArrayList<String> res=new ArrayList<>(); 
  3. if(str==null||str.length()==0){ 
  4. return res; 
  5. } 
  6. char[] chs = str.toCharArray(); 
  7. process(chs,0,res); 
  8. // res.sort(null); 
  9. return res; 
  10. } 
  11. // str[i...]范围上所有的字符,都可以在i位置上,后续都取尝试 
  12. // str[0...i-1]范围上,是之前做的选择 
  13. // 请把所有的字符串形成的全2排列,加入到res里去 
  14. private static void process(char[] chs, int i, ArrayList<String> res) { 
  15. if(i==chs.length){ 
  16. res.add(String.valueOf(chs)); 
  17. } 
  18. boolean[] visit=new boolean[26]; 
  19. for (int j = 0; j < chs.length; j++) { 
  20. if(!visit[chs[j]-'a']){ 
  21. visit[chs[j]-'a']=true; 
  22. swap(chs,i,j); 
  23. process(chs,i+1,res); 
  24. swap(chs,i,j); 
  25. } 
  26. } 
  27. } 
  28.  
1-10-2-4. 题目八:纸牌(先手|后手拿牌)

题目和例子
题目和例子

  1. public static int win1(int[] arr){ 
  2. if(arr==null||arr.length==0){ 
  3. return 0; 
  4. } 
  5. return Math.max(f(arr,0,arr.length-1),s(arr,0,arr.length-1)); 
  6. } 
  7.  
  8. private static int f(int[] arr, int i, int j) { 
  9. if(i==j){ 
  10. return arr[i]; 
  11. } 
  12. return Math.max(arr[i]+s(arr,i+1,j),arr[j]+s(arr,i,j-1)); 
  13. } 
  14.  
  15. private static int s(int[] arr, int i, int j) { 
  16. if(i==j){ 
  17. return 0; 
  18. } 
  19. return Math.min(f(arr,i+1,j),f(arr,i,j-1)); 
  20. } 
1-10-2-5. 逆序栈

给你一个栈,请你逆序这个栈,不能申请额外的数据结构,只能使用递归函数,如何实现?

过程图解
过程图解

  1. public static void reverse(Stack<Integer> stack){ 
  2. if(stack.isEmpty()){ 
  3. return; 
  4. } 
  5. int i=f(stack);//每次弹出结果 
  6. reverse(stack);//递归完结果是逆序的 
  7. stack.push(i);//按照逆序压入栈中,最终实现栈逆序 
  8. } 
  9.  
  10. public static int f(Stack<Integer> stack) { 
  11. int result=stack.pop(); 
  12. if(stack.isEmpty()){ 
  13. return result; 
  14. }else{ 
  15. int last=f(stack); 
  16. stack.push(result); 
  17. return last; 
  18. } 
  19. } 
1-10-2-6. 数字与字母转化

规定1和A对应,2和B对应,3和C对应。。。,那么一个数字字符串比如“111”就可以转化为“AAA”,“KA”和“AK”。给定一个只有数字字符组成的字符串str,返回多少种转化结果。

  1. public static int number(String str){ 
  2. if(str==null||str.length()==0){ 
  3. return 0; 
  4. } 
  5. return process(str.toCharArray(),0); 
  6. } 
  7. /* 
  8. * i之前的位置如何转化已经做过决定了 
  9. * i...有多少种转化的结果 
  10. * */ 
  11. public static int process(char[] chs, int i) { 
  12. if(i==chs.length){ 
  13. return 1; 
  14. } 
  15. if(chs[i]=='0'){ 
  16. return 0;//之前转后导致当前的0无法有效转化 
  17. } 
  18. if(chs[i]=='1'){//当前字符为1时 
  19. int res=process(chs,i+1);//i 自己作为单独的部分,后续有多少种方法 
  20. if(i+1<chs.length){ 
  21. res+=process(chs,i+2);//(i和(i+1)作为单独的部分,后续有多少种算法) 
  22. } 
  23. return res; 
  24. } 
  25.  
  26. if(chs[i]=='2'){//当前字符为2时 
  27. int res=process(chs,i+1);// i自己作为单独的部分,后续有多少种方法 
  28. if(i+1<chs.length && (chs[i+1]>='0' && chs[i+1] <='6')){//0-6之间保证集合长度26 
  29. res+=process(chs,i+2); 
  30. } 
  31. return res; 
  32. } 
  33. return process(chs,i+1); 
  34. } 
1-10-2-7. 重量和价值

给定两个长度为N的数组weights和values,weights[i]和values[i]分别代表i号货品的重量和价值,给定一个正数bag,表示一个载重bag的袋子,你装的物品不能超过这个重量,返回你能装下最多的价值是多少?

  1. public static int maxValue1(int[] weights,int[] values,int bag){ 
  2. return process1(weights,values,0,0,bag); 
  3. } 
  4. // i...的货物自由选择,形成的最大价值返回;从i开始做决定形成的最大价值 
  5. // 重量永远不要超过bag 
  6. // alreadyweight之前做的决定,所达到的重量 
  7. public static int process1(int[] weights, int[] values, int i, int alreadyweight, int bag) {//可变参数少比较好,越容易改动态规划 
  8. if(alreadyweight>bag){ 
  9. return 0; 
  10. } 
  11. if(i==weights.length){ 
  12. return 0; 
  13. } 
  14.  
  15. return Math.max(process1(weights, values, i+1, alreadyweight, bag), 
  16. values[i]+process1(weights, values, i+1, alreadyweight+weights[i], bag)); 
  17. } 

尝试的代码暴力递归可以该着成位运算提高速度。

posted @ 2022-06-03 00:03  编程未来  阅读(107)  评论(0编辑  收藏  举报