这里是一个使用 Haskell 的例子,它列出并比较了所有 126 种可能的组合:
import Data.List
import Data.Ord
divide :: [a] -> [([a], [a])]
divide [] = [([],[])]
divide (x:xs) = go ([x],[],xs,1,length xs) where
go (a,b,[],i,j) = [(a,b)]
go (a,b, s@(x:xs),i,j)
| i>=j = [(a,b++s)]
| i>0 = go (x:a, b, xs, i+1, j-1) ++ go (a, x:b, xs, i-1, j-1)
| i==0 = go (x:a, b, xs, 1, j-1) ++ go (x:b, a, xs, 1, j-1)
minCombi list =
let groups = map (\x -> map (negate) (fst x) ++ snd x) (divide list)
sums = zip (map (abs . sum) groups) groups
in minimumBy (comparing fst) sums
*Main> minCombi [2, 4, 2, 6, 9, 10, 1, 7, 6, 3]
(0,[-7,-10,-2,-4,-2,1,9,6,6,3])
*主函数> minCombi [2, 4, 2, 6, 9, 10, 1, 7, 6, 3]
(0,[-7,-10,-2,-4,-2,1,9,6,6,3])