递归实现嵌套循环

huangapple go评论87阅读模式
英文:

Recursive implementation of a nested loop

问题

我正在尝试从一个字符串生成递增的组合,类似于:

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

我使用嵌套循环来实现:

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

是否可以使用递归函数来实现相同的效果?我正在使用Go语言编写,但任何语言的示例都会有所帮助。这是Playground的链接:链接

英文:

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

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

I'm doing it with nested loops:

str := &quot;23405&quot;
for i := 0; i &lt;= len(str); i++ {
	for j := 0; j &lt;= 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

得分: 2

这是我尝试使用递归的代码: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)
}

感谢nexus66的帮助~

英文:

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

package main

import &quot;fmt&quot;

func reverse(str string, length int, i int) {
  if len(str) &gt; length+i &amp;&amp; length &gt; 0 {
    fmt.Println(str[i:length+i])
    reverse(str, length, i+1)
  } else if len(str) == length+i &amp;&amp; length &gt; 0 {
    fmt.Println(str[i:length+i])
    reverse(str, length-1, 0)
  }
}

func recIterate(str string, length int, i int) {
  if length &gt; i {
    fmt.Println(str[i:len(str)-length+i+1])
    recIterate(str, length, i+1)
  } else if length == i &amp;&amp; length &gt; 0{
    recIterate(str, length-1, 0)
  }
}

func main() {
  str := &quot;234051234&quot;
  recIterate(str, len(str), 0)
  // reverse(str, len(str), 0)
}

Shout out to nexus66 for helping~

huangapple
  • 本文由 发表于 2016年12月9日 12:17:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/41053016.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定