55.go 852 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package main
  2. func canJumpIter(nums []int, visited map[int]bool, pos int) bool {
  3. if visited[pos] {
  4. return false
  5. }
  6. visited[pos] = true
  7. if pos+nums[pos] >= len(nums)-1 {
  8. return true
  9. }
  10. if nums[pos] == 0 {
  11. return false
  12. }
  13. for i := 1; i <= nums[pos]; i++ {
  14. if canJumpIter(nums, visited, pos+i) {
  15. return true
  16. }
  17. }
  18. return false
  19. }
  20. // TLE
  21. func canJumpOld(nums []int) bool {
  22. return canJumpIter(nums, map[int]bool{}, 0)
  23. }
  24. func canJump(nums []int) bool {
  25. // leap: the longest distance of jumping at idx 'i'
  26. for i, leap := 0, 0; i < len(nums); i, leap = i+1, leap-1 {
  27. if leap < 0 {
  28. return false
  29. }
  30. if nums[i] > leap {
  31. leap = nums[i]
  32. }
  33. }
  34. return true
  35. }
  36. /* func main() {
  37. a1 := []int{2, 3, 1, 1, 4}
  38. a2 := []int{3, 2, 1, 0, 4}
  39. a3 := []int{0}
  40. fmt.Println(canJump(a1))
  41. fmt.Println(canJump(a2))
  42. fmt.Println(canJump(a3))
  43. } */