记录精彩的程序人生

Golang 对字符串数组全排列

如题,见代码:


package main  
 
import "fmt" 

func main() { 

	arr := []string{'a','c','d'}
	result := permute(arr)
	fmt.Println(result)
}

func permute(nums []string) [][]string {
	res := [][]string{}
	visited := map[string]bool{}

	var dfs func(path []string)
	dfs = func(path []string) {
		if len(path) == len(nums) {
			temp := make([]string, len(path))
			copy(temp, path)
			res = append(res, temp)
			return
		}
		for _, n := range nums {
			if visited[n] {
				continue
			}
			path = append(path, n)
			visited[n] = true
			dfs(path)
			path = path[:len(path)-1]
			visited[n] = false
		}
	}
	dfs([]string{})
	return res
}

执行打印结果如下:

[[a c d] [a d c] [c a d] [c d a] [d a c] [d c a]]
请成为永远疯狂永远浪漫永远清澈的存在。

留下你的脚步