Merge pull request #312 from yuxiaoba/master

加入迭代部分golang代码
This commit is contained in:
wangzheng0822 2019-05-20 16:01:33 +08:00 committed by GitHub
commit 3e64f88d97
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 146 additions and 0 deletions

View File

@ -0,0 +1,31 @@
package Recursion
// 迭代实现阶乘
type Fac struct {
val map[int]int
}
func NewFactorial(n int) *Fac {
return &Fac{
make(map[int]int, n),
}
}
func (fac *Fac) Factorial(n int) int {
if fac.val[n] != 0{
return fac.val[n]
}
if n <= 1{
fac.val[n] = 1
return 1
}else {
res := n * fac.Factorial(n-1)
fac.val[n] =res
return res
}
}
func (fac *Fac) Print(n int ) {
println(fac.val[n])
}

View File

@ -0,0 +1,11 @@
package Recursion
import "testing"
func TestFac_Factorial(t *testing.T) {
fac := NewFactorial(10)
for i:=1; i<15; i++{
fac.Factorial(i)
fac.Print(i)
}
}

View File

@ -0,0 +1,35 @@
package Recursion
import "fmt"
// 递归实现斐波那契数列
type Fibs struct {
val map[int]int // 使用字典存储结果
}
func NewFibs(n int) *Fibs {
return &Fibs{
make(map[int]int, n),
}
}
func (fib *Fibs)Fibonacci(n int) int {
if fib.val[n] != 0{
return fib.val[n]
}
if n <= 1 {
fib.val[1] = 1
return 1
}else if n ==2{
fib.val[2] = 1
return 1
} else {
res := fib.Fibonacci(n-1) + fib.Fibonacci(n-2)
fib.val[n] = res
return res
}
}
func (fib *Fibs)Print(n int) {
fmt.Println(fib.val[n])
}

View File

@ -0,0 +1,11 @@
package Recursion
import "testing"
func TestFibs_Fibonacci(t *testing.T) {
fib := NewFibs(10)
for i:=1; i<15; i++{
fib.Fibonacci(i)
fib.Print(i)
}
}

View File

@ -0,0 +1,40 @@
package Recursion
import (
"fmt"
)
// 实现一组数据集合的全排列
type RangeType struct {
value []interface{}
}
func NewRangeArray(n int) *RangeType {
return &RangeType{
make([]interface{},n),
}
}
func (slice *RangeType)RangeALL( start int) {
len := len(slice.value)
if start == len-1{
// 如果已经是最后位置,直接将数组数据合并输出
fmt.Println(slice.value)
}
for i:=start; i<len; i++{
// i = start 时输出自己
// 如果i和start的值相同就没有必要交换
if i==start || slice.value[i] != slice.value[start]{
//交换当前这个与后面的位置
slice.value[i], slice.value[start] = slice.value[start], slice.value[i]
//递归处理索引+1
slice.RangeALL(start+1)
//换回来,因为是递归,如果不换回来会影响后面的操作,并且出现重复
slice.value[i], slice.value[start] = slice.value[start], slice.value[i]
}
}
}

View File

@ -0,0 +1,18 @@
package Recursion
import "testing"
func TestRangeALL(t *testing.T) {
slice1 := NewRangeArray(4)
for i:=0; i<4; i++{
slice1.value[i] = i+1
}
slice1.RangeALL(0)
slice2 := NewRangeArray(3)
slice2.value[0] = "a"
slice2.value[1] = "b"
slice2.value[2] = "c"
slice2.RangeALL(0)
}