这是一种方法F#
:
open System
open System.Collections.Generic
let pad = new Dictionary<int, string>()
pad.Add(2, "A,B,C")
pad.Add(3, "D,E,F")
pad.Add(4, "G,H,I")
let permutations = new List<string>()
let rec permute(digits: int list, alphas: string list) =
if List.length digits > 0 && List.length alphas = 0 then
permute(digits, ["#"] |> List.append (pad.[digits.[0]].Split([|','|]) |> List.ofArray))
else
match alphas with
| [_] ->
match digits with
| h::t -> permute(t, [])
| _ -> ()
| h::t ->
for i = 0 to List.length alphas - 2 do
permutations.Add(h + alphas.[i])
for j = 1 to List.length digits - 1 do
let others = pad.[digits.[j]].Split([|','|])
for o in others do
permutations.Add(h + o)
permute(digits, t)
| _ -> ()
permute([2;3;4;], [])
seq {
for o in permutations do
yield o
yield o.[1].ToString() + o.[0].ToString()
}
|> Seq.distinct
|> Seq.sort
|> Seq.iter(fun s -> Console.WriteLine(s))
;;
输出
[2; 3; 4]
[]
[2; 3; 4]
[A; B; C; ... ]
AA
AB
AC
AD
AE
AF
AG
AH
AI
[2; 3; 4]
[B; C; #]
BB
BC
BD
BE
BF
BG
BH
BI
[2; 3; 4]
[C; #]
CC
CD
CE
CF
CG
CH
CI
[2; 3; 4]
[#]
[3; 4]
[]
[3; 4]
[D; E; F; ... ]
DD
DE
DF
DG
DH
DI
[3; 4]
[E; F; #]
EE
EF
EG
EH
EI
[3; 4]
[F; #]
FF
FG
FH
FI
[3; 4]
[#]
[4]
[]
[4]
[G; H; I; ... ]
GG
GH
GI
[4]
[H; I; #]
HH
HI
[4]
[I; #]
II
[4]
[#]
[]
[]
AA
AB
AC
AD
AE
AF
AG
AH
AI
BA
BB
BC
BD
BE
BF
BG
BH
BI
CA
CB
CC
CD
CE
CF
CG
CH
CI
DA
DB
DC
DD
DE
DF
DG
DH
DI
EA
EB
EC
ED
EE
EF
EG
EH
EI
FA
FB
FC
FD
FE
FF
FG
FH
FI
GA
GB
GC
GD
GE
GF
GG
GH
GI
HA
HB
HC
HD
HE
HF
HG
HH
HI
IA
IB
IC
ID
IE
IF
IG
IH
II