F# 算法贴——从数字列表中,任意三个相加为指定值的所有组合。
fsharp吧
全部回复
仅看楼主
level 9
君女子 楼主
一楼先开辟个内存....
2012年06月25日 07点06分 1
level 9
君女子 楼主
代码:
let GetThreeNum input list =
...let listSort = list |> List.sortBy(fun x -> -x)
...Seq.distinct (
......seq {
.........for n1 in listSort do
.........for n2 in listSort do
.........for n3 in listSort do
............if n1 + n2 + n3 = input && n1 >= n2 && n2 >= n3 then yield (n1,n2,n3)
.........})
2012年06月25日 07点06分 2
引用自:@hadstj let rec powerset = function | [] -> [[]] | h::t -> List.fold (fun xs e -> (h::e)::e::xs) [] (powerset t); powerset [0;1;2;3;5;7;9;11;4] |> List.filter(fun i -> i.Length = 3) |> List.filter(fun i -> List.sum(i) = 12)
2014年05月09日 07点05分
level 9
君女子 楼主
验证:
let res = GetThreeNum 12 [0;1;2;3;5;7;9;11]
for n in res do
printfn "%A" n
结果:
(11, 1, 0)
(9, 3, 0)
(9, 2, 1)
(7, 5, 0)
(7, 3, 2)
(5, 5, 2)
2012年06月25日 07点06分 3
level 9
君女子 楼主
自己支持一个;
[抛媚眼]
2012年06月25日 07点06分 4
level 7
[玩铃铛]
2012年06月25日 09点06分 5
level 7
[求你了]
2012年06月25日 22点06分 6
level 7
[没有钱]
2012年06月25日 22点06分 7
level 9
君女子 楼主
[拿玩偶],自己顶
2012年06月26日 00点06分 8
level 9
君女子 楼主
[玩铃铛][开心]
2012年06月26日 00点06分 9
level 9
君女子 楼主
吧里的人气确实有点弱。。[眺望]
2012年06月26日 00点06分 10
[揉脸],相当滴弱,,多少人不知道有这门语言,,多少人平时根本就不会用这门语言,,
2012年06月26日 09点06分
我是尝到了一些甜头,虽然资料难找,坚持学一段时间,小有点成就感 [打]
2012年06月27日 00点06分
@君女子 [我爱牛奶],,
2012年06月30日 00点06分
level 7
[有木有]、、
2012年06月26日 09点06分 11
level 9
君女子 楼主
本算法有写优化的地方。
let GetThreeNum input list =
...let listSort = list |> List.sortBy(fun x -> -x)
...seq {
......for n1 in listSort do
......for n2 in listSort do
......for n3 in listSort do
.........if n1 + n2 + n3 = input && n1 >= n2 && n2 >= n3 then yield (n1,n2,n3)
......}
只要输入的list没有重复的成员,就不用distinct了。
[阿狸侠]

2012年06月27日 00点06分 12
level 9
君女子 楼主
百度贴吧居然不能修改自己的发言,
所以,说话要负责啊....
[给力]
2012年06月27日 00点06分 13
[飘过],如果可以修改的话,也太神奇了吧、、
2012年06月30日 00点06分
level 9
君女子 楼主
[顶][顶]
[给力][这个屌]

2012年07月03日 00点07分 14
level 9
君女子 楼主
[爬来了][遁]
2012年07月03日 00点07分 15
level 13
[揉脸]
2012年07月29日 09点07分 16
level 7
[拿玩偶],赶脚好厉害哇,,……
2012年12月04日 04点12分 17
level 10
let rec subsets s =
set [ yield s
for e in s do
yield! subsets (Set.remove e s)]
|> Set.toList
subsets (set [0;1;2;3;5;7;9;11])
|> List.filter(fun i -> i.Count = 3)
|> List.map(fun i -> Set.toList i)
|> List.filter(fun i -> List.sum(i) = 12)
2013年02月05日 07点02分 18
[真棒]。收藏
2014年04月17日 08点04分
level 10

let rec powerset = function
| [] -> [[]]
| h::t -> List.fold (fun xs e -> (h::e)::e::xs) [] (powerset t);
powerset [0;1;2;3;5;7;9;11;4]
|> List.filter(fun i -> i.Length = 3)
|> List.filter(fun i -> List.sum(i) = 12)
2013年02月05日 10点02分 19
[真棒]。继续收藏
2014年04月17日 08点04分
level 9
君女子 楼主
@hadstj
大牛在这里。丢了一段时间,又给忘光光了。好好学习,天天向钱。[钱币]
2014年04月17日 08点04分 20
1