在java库中是否有内置方法可以为任何N,R计算'N choose R'?
我正在研究一个难题,包括分析所有大小的k子集并找出哪一个是最优的.我写了一个解决方案,当子集的数量很少时可以工作,但是对于更大的问题,它会耗尽内存.现在我正在尝试将用python编写的迭代函数转换为java,以便我可以在创建时分析每个子集,只获得表示它是如何优化的值,而不是整个集合,这样我就不会用完记忆.到目前为止,这是我所拥有的,即使是非常小的问题,它似乎也没有完成:
public static LinkedList<LinkedList<Integer>> getSets(int k, LinkedList<Integer> set)
{
int N = set.size();
int maxsets = nCr(N, k);
LinkedList<LinkedList<Integer>> toRet = new LinkedList<LinkedList<Integer>>();
int remains, thresh;
LinkedList<Integer> newset;
for (int i=0; i<maxsets; i++)
{
remains = k;
newset = new LinkedList<Integer>();
for (int val=1; val<=N; val++)
{
if (remains==0)
break;
thresh = nCr(N-val, remains-1);
if (i < thresh)
{
newset.add(set.get(val-1));
remains --;
}
else
{
i -= thresh;
}
}
toRet.add(newset);
}
return toRet;
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮我调试这个函数或建议另一个迭代生成大小k子集的算法吗?
编辑:我终于使这个功能工作,我不得不创建一个新的变量,与我做的相同,我和thresh比较,因为python处理循环索引不同.