seo网站怎么做,木马工业产品设计公司,营销型网站建设调查表,移动网站推广如何优化118. 杨辉三角 思路#xff1a;
找规律#xff0c;每一行的第一个元素和最后一个元素都是1#xff0c;其中中间需要改变的数找对应的规律
比如第二行#xff08;从0开始#xff09;的2#xff0c;是dp[1][0] dp[1][1]。类似的找出对应的规律
代码#xff1a;
clas… 118. 杨辉三角 思路
找规律每一行的第一个元素和最后一个元素都是1其中中间需要改变的数找对应的规律
比如第二行从0开始的2是dp[1][0] dp[1][1]。类似的找出对应的规律
代码
class Solution {
public:vectorvectorint generate(int numRows) {vectorvectorint dp;for(int i 0; i numRows; i){vectorint line(i 1);line[0] line[i] 1;for(int j 1; j i; j){line[j] dp[i - 1][j - 1] dp[i - 1][j];}dp.push_back(line);}return dp;}
}; 119. 杨辉三角 II 思路
和上面一样只是返回需要的那一行的数组
代码
class Solution {public ListInteger getRow(int rowIndex) {ListListInteger ret new ArrayListListInteger();for(int i 0; i rowIndex; i){ListInteger row new ArrayListInteger();for(int j 0; j i; j){if(j 0 || j i){row.add(1);}else{row.add(ret.get(i - 1).get(j - 1) ret.get(i - 1).get(j));}}ret.add(row);}return ret.get(rowIndex);}
} 661. 图片平滑器 思路
其实就是对应的每个点看他八个邻居的值如果在原数组的范围就加起来求和然后求平均值如果超出就不加。
代码
class Solution {public int[][] imageSmoother(int[][] img) {int m img.length, n img[0].length;int[][] ret new int[m][n];int[][] dis new int[][]{{0,0} , {1, 0}, {-1,0}, {0, -1}, {0, 1}, {-1, -1}, {-1, 1}, {1, 1}, {1, -1}};for(int i 0; i m; i){for(int j 0; j n; j){int num 0, sum 0;for(int[] di : dis){int next_m i di[0], next_n j di[1];if(next_m 0 || next_m m || next_n 0 || next_n n){continue;}sum img[next_m][next_n];num ;}ret[i][j] sum / num;}}return ret;}
} 598. 范围求和 II 思路 这个黄色的2下面也包含了[3,3]所以我们发现左上角的(0,0)肯定是累加之后最大的所以我们需要找到右下角和(0,0)一样的情况所以就看ops里面最小的数组。
代码
class Solution {public int maxCount(int m, int n, int[][] ops) {for(int[] op :ops){m Math.min(m, op[0]);n Math.min(n, op[1]);}return m * n;}
} 419. 甲板上的战舰 思路
我们假定只看左上角那么会有两个情况当当前左边为x
左边的索引和上边的索引小于0他的左边和上边都没有X
代码
class Solution {public int countBattleships(char[][] board) {int count 0;int m board.length, n board[0].length;for(int i 0; i m;i ){for(int j 0; j n; j){if(board[i][j] X (i 0 || board[i - 1][j] ! X) (j 0 ||board[i][j - 1] ! X)){count ;}}}return count;}
}