classSolution{List<Integer> ans =newArrayList<>();publicList<Integer>spiralOrder(int[][] matrix){// 试试递归recursion(matrix,0, matrix.length -1,0, matrix[0].length -1);return ans;}// 一次一圈voidrecursion(int[][] matrix,int low,int height,int left,int right){if(low > height || left > right){return;}// 一行情况if(height == low){for(int i = left; i <= right; i++){ans.add(matrix[low][i]);}return;}// 一列情况elseif(left == right){for(int i = low; i <= height; i++){ans.add(matrix[i][left]);}return;}// 其他情况for(int i = left; i <= right; i++){ans.add(matrix[low][i]);}for(int i = low +1; i <= height; i++){ans.add(matrix[i][right]);}for(int i = right -1; i >= left; i--){ans.add(matrix[height][i]);}for(int i = height -1; i > low; i--){ans.add(matrix[i][left]);}recursion(matrix, low +1, height -1, left +1, right -1);}}
迭代
贴一贴吧,不过看递归的也够了
classSolution{publicList<Integer>spiralOrder(int[][] matrix){// 迭代写法List<Integer> ans =newArrayList<>();// 一行的情况if(matrix.length ==1){for(int i =0; i < matrix[0].length; i++){ans.add(matrix[0][i]);}return ans;}if(matrix[0].length ==1){for(int i =0; i < matrix.length; i++){ans.add(matrix[i][0]);}return ans;}// 碰壁改变方向,更新墙壁值int left =0, right = matrix[0].length -1;int low =1, height = matrix.length -1;// 右 -》 下,下 -》左,左 -》上,上 => 右边// 右下左上 0,1,2,3int[][] directions =newint[][]{{0,1},{1,0},{0,-1},{-1,0}};int forDir =0;int[] direction = directions[forDir];int x =0, y =0;ans.add(matrix[x][y]);boolean flag =true;while(flag){flag =false;if(forDir ==0){while(y +1<= right){ans.add(matrix[x][y +1]);flag =true;y++;}forDir++;right--;}elseif(forDir ==1){while(x +1<= height){ans.add(matrix[x +1][y]);flag =true;x++;}forDir++;height--;}elseif(forDir ==2){while(y -1>= left){ans.add(matrix[x][y -1]);flag =true;y--;}forDir++;left++;}elseif(forDir ==3){while(x -1>= low){ans.add(matrix[x -1][y]);flag =true;x--;}forDir =0;low++;}}return ans;}}
文章目录路径总和 I路径总和 II比较简单,就连着一起写了 路径总和 I
注意:一定得走到叶子才算 直接看代码吧,注释也就几行。
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* T…
php中文网最新课程每日17点准时技术干货分享打印输出函数说明echo输出一个或多个字符串print输出字符串printf输出格式化字符串sprintfReturn a formatted stringfprintf将格式化后的字符串写入到流sscanf根据指定格式解析输入的字符vfprintf将格式化字符串写入流vprintf输出格…