在这个问题中,您将获得一个值V和一个唯一整数列表.您的工作是找到大小为4的不同子集的数量,总计为V.列表中的每个元素只能使用一次.如果找不到这样的子集,则输出0.
例如,如果整数是[3, 4, 5, 6, 7, 8, 9, 10]和值30,则输出应为5.子集是:
[3, 8, 9, 10]
[4, 7, 9, 10]
[5, 6, 9, 10]
[5, 7, 8, 10]
[6, 7, 8, 9].
Run Code Online (Sandbox Code Playgroud)
解决这个问题并不难,最直接的方法是嵌套for循环四次.什么是Clojure方式呢?
我将如何做到这一点:
(ns example.solve
(:require [clojure.math.combinatorics :as combo]))
(defn solve
[s n v]
(filter (comp (partial = v)
(partial reduce +))
(combo/combinations s n)))
Run Code Online (Sandbox Code Playgroud)
我math.combinatorics在我的例子中使用,因为这是从列表中获取4个元素的所有组合的最简单方法.
以下是使用示例solve:
=> (solve [3 4 5 6 7 8 9 10] 4 30)
((3 8 9 10) (4 7 9 10) (5 6 9 10) (5 7 8 10) (6 7 8 9))
Run Code Online (Sandbox Code Playgroud)