老哥版permutation

v1:

package main

import (
   "fmt"
)

func permutate(collection [][]rune, plus rune) (newCollection [][]rune) {
    if len(collection) == 0 {
        newCollection = [][]rune{{plus}}
        return
    }
    newCollection = make([][]rune, 0)
    for _, orignalArr := range collection {
        oldLength := len(orignalArr)
        newLength := oldLength + 1
        for i := 0; i < newLength; i++ {
            newArr := make([]rune, newLength)
            newArr[i] = plus
            for orignalKey, originalValue := range orignalArr {
                var newKey int
                if orignalKey < i {
                    newKey = orignalKey
                } else {
                    newKey = orignalKey + 1
                }
                newArr[newKey] = originalValue
            }
            newCollection = append(newCollection, newArr)
        }
    }
    return
}

func getAllPermutations(s string) []string {
    arr := []rune(s)
    collection := [][]rune{}
    for _, e := range arr {
        collection = permutate(collection, e)
    }
    strCollection := make([]string, 0, len(collection))
    for _, charArr := range collection {
        strCollection = append(strCollection, string(charArr))
    }
    return strCollection
}

func main() {
    fmt.Println(getAllPermutations("abcd"))
}

v2:

package main

import (
    "fmt"
)

func processPermutations(s string, procedure func(string)) {
    elements := []rune(s)
    length := len(elements)
    var permutate func([]rune, int)
    permutate = func(elements []rune, from int) {
        if from == length-1 {
            procedure(string(elements))
        }
        var elementsCopy []rune = make([]rune, length)
        for i := from; i < length; i++ {
            copy(elementsCopy, elements)
            elementsCopy[from], elementsCopy[i] = elementsCopy[i], elementsCopy[from]
            permutate(elementsCopy, from+1)
        }
    }
    permutate(elements, 0)
}

func main() {
    processPermutations("abcd", func(s string) {
        fmt.Println(s)
    })
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值