按照以下方案跳:跳1个单位到第二块石头,再跳2个单位到第三块石头,再跳2个单位到第四块石头,再跳3个单位到第六块石头,再跳4个单位到第七块石头。最后,
解题思路分析1。递归;时间复杂度为o (n 2),空间复杂度为o (n 2)
var m[][]int func可以跨(stones[]int)bool { n:=len(stones)m=make([][][][]int,n)for I:=0;I n;i { m[i]=make([]int,n)for j:=0;j n;j { m[i][j]=-1 } } return dfs(stones,0,0)==1}func dfs(stones []int,index int,k int)int { if m[index][k]=0 { return m[index][k]} for I:=index 1;我len(石头);I { next:=stones[I]-stones[index]if k-1=next next=k 1 {//k-1、k或k 1 if dfs(stones,I,next)==1 { m[index][k]=1 return 1 } } } if index==len(stones)-1 { m[index][k]=1 } else { m[index][k]=0 } return m[index][k]} 2、动态规划;时间复杂度O(n^2),
func可以跨(stones[]int)bool { n:=len(stones)m:=make(map[int]map[int]int)for I:=0;I n;I { m[stones[I]]=make(map[int]int)} m[0][0]=1 for I:=0;I n;I { for k:=range m[stones[I]]{ for next:=k-1;next=k 1;next { if next 0 { if _,ok:=m[stones[I]next];ok { m[stones[I]next][next]=1 } } } return len(m[stones[n-1]])0 } 3、动态规划;时间复杂度O(n^2),
func可以跨(stones[]int)bool { n:=len(stones)DP:=make([][]bool,n 1)for I:=0;I n;i { dp[i]=make([]bool,n 1)} DP[0][0]=true for I:=0;I n;I { for j:=0;j I;j { k:=stones[I]-stones[j]if k=I { DP[I][k]=DP[j][k-1]| | DP[j][k]| | DP[j][k]//满足其一if I==n-1dp[I][k]==true { return true } } } return false } 4、动态规划;时间复杂度O(n^2),
type Node struct { index int size int } func可以跨(stones[]int)bool { n:=len(stones)m:=make(map[int]bool)for I:=0;I n;I { m[stones[I]]=true }被访问:=make(map[Node]bool)stack:=make([]Node,0) node :=Node{ index: 0,size: 0,} stack=append(stack,Node)被访问[Node]=true for len(stack)0 { Node=stack[len(stack)-1]stack=stack[:len(stack)-1]if Node。对于k:=Node,index==stones[n-1]{ return true }。尺码-1;k=节点。尺寸1;k { next:=Node。index k if k stones[n-1]{ continue } temp:=Node { index:next,size: k,} if k 0m[next]==true被访问[temp]==false { is visited[temp]=true stack=append(stack,temp)} } return false }总结困难的题目,
标题:leetcode403_go_青蛙过河
链接:https://www.52hkw.com/news/rj/73543.html
版权:文章转载自网络,如有侵权,请联系删除!