数据结构刷题基础版

耶比耶比,也祝自己节日快乐鸭 ,还有,要好好学习

目录

1.杨辉三角

2.重塑矩阵


1.杨辉三角

118. 杨辉三角 - 力扣(LeetCode) (leetcode-cn.com)https://leetcode-cn.com/problems/pascals-triangle/submissions/

题目及示例:

解题思路:(注意在列表中仍有列表)

①转换的思想(联想到将杨辉三角转换成矩阵来进行思考)

②灵活运用有关于集合的内容

 代码如下:

class Solution {
 public List<List<Integer>> generate(int numRows) {
        List<List<Integer>>tmp=new ArrayList<>();
        int [][]nums=new int[numRows][numRows];
        for(int i=0;i<nums.length;i++){
            List<Integer>list=new ArrayList<>();
            for(int j=0;j<=i;j++){
                if(j==0||i==j){
                    nums[i][j]=1;
                }else{
                    nums[i][j]=nums[i-1][j-1]+nums[i-1][j];
                }list.add(nums[i][j]);
            }
            tmp.add(list);
        }return tmp;
 }
}

2.重塑矩阵

566. 重塑矩阵 - 力扣(LeetCode) (leetcode-cn.com)https://leetcode-cn.com/problems/reshape-the-matrix/

题目及示例:

解题思路:(转换思想,一维数组和二维数组的相互转换) 

①将二维数组转换为一维数组

②再将一维数组转换成为所需要的二维数组

a.关于如何将二维数组变成一维数组

b.以本题为例的分析

代码如下:

class Solution {
    public int[][] matrixReshape(int[][] mat, int r, int c) {
   //把二维数组看做一维数组后求数组的长度
   int m=mat.length;
   //每个被看做一维数组的对应的长度
   int n=mat[0].length;
   //简单判断,若二维数组切换前后数据的数量发生了改变,那么显然是不能够进行成功切换的
   if(m*n!=r*c){
       return mat;
   }
   //创建一个新数组用来接收r行,c列的数组
   int tmp[][]=new int[r][c];
   //判断二维数组中每个数在变成一维数组后的位置
   int newposition=0;
   for(int i=0;i<r;i++){
       for(int j=0;j<c;j++){
           tmp[i][j]=mat[newposition/n][newposition%n];
           newposition++;
       }
   }return tmp;
}
}

猜你喜欢

转载自blog.csdn.net/weixin_58850105/article/details/123350945