算法- 两种方式实现上楼梯递归和动态规划

2022-04-27 19:26:39 浏览数 (1)

代码语言:javascript复制
package step

import (
   "fmt"
)
var count = 0
func UpStep(canChoose,iChoose []int,all int) {
   if all < 0 {
      return
   }
   if all == 0 {
      //fmt.Println(iChoose)
      count  
      return
   }
   for _,choose := range canChoose {
      cho := append(iChoose,choose)
      UpStep(canChoose,cho,all - choose)
   }
}
/*
 将每个台阶的值用数组存下 思想也是从少到多,
 */
func UpStep1(canChoose []int,all int) {
   if all < 0 {
      return
   }
   var iChoose []int
   for i := 0;i <= all;i  {
      iChoose = append(iChoose,0)
   }
   for _,cho := range canChoose {
      iChoose[cho] = 1
   }
   for i := 1; i <= all ; i   {
      for _,cho := range canChoose {
         if i - cho < 1 {
            continue
         }
         iChoose[i] = iChoose[i]   iChoose[i - cho]
      }
   }
   fmt.Println(iChoose[all])
   fmt.Println(iChoose)
}

0 人点赞