classSolution{publicstaticbooleandfs(char[][] board,char[] word,int i,int j,int k){// 2. 判断越界if(i>=board.length || i<0|| j>=board[0].length || j<0|| board[i][j]!= word[k])returnfalse;// 3. 判断单词单词结束if(k==word.length-1)returntrue;// 4. 先设为空 防止重复访问
board[i][j]=' ';// 5. 检查四个方向boolean res =dfs(board, word, i+1, j, k+1)||dfs(board, word, i-1, j, k+1)||dfs(board, word, i, j+1, k+1)||dfs(board, word, i, j-1, k+1);
board[i][j]= word[k];return res;}publicbooleanexist(char[][] board,String word){char[] words = word.toCharArray();// 1. 遍历二维数组for(int i =0; i < board.length; i++){for(int j =0; j < board[0].length; j++){// 只有true才返回, false继续遍历if(dfs(board, words, i, j,0))returntrue;}}returnfalse;}}
14- I. 剪绳子
classSolution{publicintcuttingRope(int n){int[] dp =newint[n+1];
dp[2]=1;for(int i =0; i < n+1; i++){for(int j =0; j < i; j++){
dp[i]=Math.max(dp[i],Math.max(j*(i-j), j*dp[i-j]));}}return dp[n];}}
15. 二进制中1的个数
publicclassSolution{// you need to treat n as an unsigned valuepublicinthammingWeight(int n){int data=0;while(n!=0){if((n&1)==1) data++;
n = n>>>1;}return data;}}
16. 数值的整数次方
classSolution{publicdoublemyPow(double x,int n){if(x ==0)return0;long b = n;double res =1.0;if(b <0){
x =1/ x;
b =-b;}while(b >0){if((b &1)==1) res *= x;
x *= x;
b >>=1;}return res;}}