# 有1、2、3、4个数字，能组成多少个互不相同 且无重复数字的三位数？都是多少？

## 传统解法

func useNormal() []int {
var ret []int
for i := 1; i < 5; i++ {
for j := 1; j < 5; j++ {
for k := 1; k < 5; k++ {
if i != j && j != k && i != k {
ret = append(ret, i*100+j*10+k)
}
}
}
}
return ret
}


## 递归求解

func useRecursion() []int {
var (
data   = []int{1, 2, 3, 4}
numLen = 3
tmp    = make([]int, numLen)
ret    []int
)
findNum(data, tmp, numLen, &ret)
return ret
}

func findNum(data, tmp []int, dep int, ret *[]int) {
for i, v := range data {
if dep--; dep < 0 {
sum := 0
for i := len(tmp) - 1; i >= 0; i-- {
sum = sum*10 + tmp[i]
}
*ret = append(*ret, sum)
return
}
tmp[dep] = v // 当前选择赋值

next := make([]int, 0, len(data))
next = append(next, data[:i]...)
next = append(next, data[i+1:]...)
findNum(next, tmp, dep, ret) // 剔除当前元素,进入下一级筛选

dep++
}
}


## 完整代码

[123 124 132 134 142 143 213 214 231 234 241 243 312 314 321 324 341 342 412 413 421 423 431 432] 24
[123 124 132 134 142 143 213 214 231 234 241 243 312 314 321 324 341 342 412 413 421 423 431 432] 24

package main

import "fmt"

func main() {
ret0 := useNormal()
fmt.Println(ret0, len(ret0))
ret1 := useRecursion()
fmt.Println(ret1, len(ret1))
}

func useNormal() []int {
var ret []int
for i := 1; i < 5; i++ {
for j := 1; j < 5; j++ {
for k := 1; k < 5; k++ {
if i != j && j != k && i != k {
ret = append(ret, i*100+j*10+k)
}
}
}
}
return ret
}

func useRecursion() []int {
var (
data   = []int{1, 2, 3, 4}
numLen = 3
tmp    = make([]int, numLen)
ret    []int
)
findNum(data, tmp, numLen, &ret)
return ret
}

func findNum(data, tmp []int, dep int, ret *[]int) {
for i, v := range data {
if dep--; dep < 0 {
sum := 0
for i := len(tmp) - 1; i >= 0; i-- {
sum = sum*10 + tmp[i]
}
*ret = append(*ret, sum)
return
}
tmp[dep] = v // 当前选择赋值

next := make([]int, 0, len(data))
next = append(next, data[:i]...)
next = append(next, data[i+1:]...)
findNum(next, tmp, dep, ret) // 剔除当前元素,进入下一级筛选

dep++
}
}


## 总结

posted @ 2021-07-18 14:24  janbar  阅读(154)  评论(0编辑  收藏  举报