doutuobao4004 2016-12-09 04:17
浏览 48

嵌套循环的递归实现

I'm trying to generate incremental combinations from a string, like:

// for "23405"
2
3
4
5
23
34
40
05
234
340
405
2340
3405
23405

I'm doing it with nested loops:

str := "23405"
for i := 0; i <= len(str); i++ {
    for j := 0; j <= i; j++ {
        fmt.Println(str[j:i])
    }
}

Is it possible to do the same with recursive function? I'm writing it with go but an example in any language would be helpful. Here's the playground link.

  • 写回答

1条回答 默认 最新

  • doushantun0614 2016-12-09 05:48
    关注

    Here's my attempt of recursion: https://repl.it/ElYY/9

    package main
    
    import "fmt"
    
    func reverse(str string, length int, i int) {
      if len(str) > length+i && length > 0 {
        fmt.Println(str[i:length+i])
        reverse(str, length, i+1)
      } else if len(str) == length+i && length > 0 {
        fmt.Println(str[i:length+i])
        reverse(str, length-1, 0)
      }
    }
    
    func recIterate(str string, length int, i int) {
      if length > i {
        fmt.Println(str[i:len(str)-length+i+1])
        recIterate(str, length, i+1)
      } else if length == i && length > 0{
        recIterate(str, length-1, 0)
      }
    }
    
    func main() {
      str := "234051234"
      recIterate(str, len(str), 0)
      // reverse(str, len(str), 0)
    }
    

    Shout out to nexus66 for helping~

    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法