免费网站模板代码,phyton 网站开发,网站建设教程 pdf,怎么用asp做网站LC-杨辉三角-记忆版
上一篇#xff1a;LC-杨辉三角
上一篇讲了杨辉三角的算法#xff0c;不过之前的算法存在一个问题#xff0c;比如#xff1a;
a[5][3] a[4][2] a[4][3]
a[5][4] a[4][3] a[4][4]我们可以看到计算a[5][3]和a[5][4]时都需要a[4][3]的值#xff0c…LC-杨辉三角-记忆版
上一篇LC-杨辉三角
上一篇讲了杨辉三角的算法不过之前的算法存在一个问题比如
a[5][3] a[4][2] a[4][3]
a[5][4] a[4][3] a[4][4]我们可以看到计算a[5][3]和a[5][4]时都需要a[4][3]的值之前我们是需要每次用到都重新计算这样就比较耗时有没有办法记住已经算过的值呢当下次用的时候直接获取就不用重新计算了以空间来换取时间。 我们可以新增一个二维数组把计算的结果放到数组中每次计算前先查看一下数组中是否存在如果已存在就获取值不存在再计算。 下面是修改后的代码 public ListListInteger generate(int numRors){int[][] catchs new int[numRors][numRors];ListListInteger a new ArrayListListInteger();for (int k 0; k numRors; k) {List temp new ArrayList();for (int l 0; l k; l) {System.out.print(f(catchs,k, l) );temp.add(f(catchs,k, l));}a.add(temp);System.out.println();}return a;}private int f(int[][] catchs,int i, int j) {//0 1if (j 0 || i j) {return 1;}if(catchs[i][j] ! 0){return catchs[i][j];}int i1 f(catchs, i - 1, j - 1) f(catchs, i - 1, j);catchs[i][j] i1;return i1;}