leetcode Day67 剑指12

31 阅读1分钟

剑指 Offer 12. 矩阵中的路径

var exist = function(board, word) {
    for(let i=0;i<board.length;i++){
        for(let j=0;j<board[0].length;j++){
            if(board[i][j]===word[0]){
                if(search(board,word,i,j)){
                    return true
                }
            }
        }
    }
    function search(b,w,i,j){
    if(w==='')return true 
    if(!(i>=0)|| !(i<b.length) ||!(j>=0) || !(j<b[i].length)){
        return false
    }
    if(b[i][j]!==w[0])return false
    let temp=b[i][j]
    b[i][j]='#'
    if(search(b,w.slice(1),i+1,j) ||
    search(b,w.slice(1),i-1,j) ||
    search(b,w.slice(1),i,j+1) ||
    search(b,w.slice(1),i,j-1)){
        b[i][j]=temp
        return true
    }
    else{
        b[i][j]=temp
        return false
    }
  }
  return false
};

剑指 Offer 14- I. 剪绳子

var cuttingRope = function(n) {
    const dp=new Array(n+1).fill(0)
    dp[1]=1
    for(let i=2;i<=n;i++){
        for(let j=1;j<=i-1;j++){
            let temp=Math.max(dp[j]*(i-j),(i-j)*j)
            dp[i]=Math.max(dp[i],temp)
        }
    }
    return dp[n]
};

剑指 Offer 14- II. 剪绳子 II

var cuttingRope = function(n) {
    let arr=[0,0,1,2,4];
  if(n<5) return arr[n];
  const max=1e9+7;
  let res=1;
  while(n>=5){
      res=res%max*3;
      n=n-3;
  }
  return  res*n%max;
};