栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

所有可能的N选择K,无回音

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

所有可能的N选择K,无回音

这是一个简单的函数,它将对

k
1和
n-k
0 进行排列并返回的下一个组合
nchoosek
。它完全独立于
n
k
的值,直接从输入数组中获取值。

function [nextc] = nextComb(oldc)   nextc = [];   o = find(oldc, 1);      %// find the first one   z = find(~oldc(o+1:end), 1) + o;   %// find the first zero *after* the first one   if length(z) > 0      nextc = oldc;      nextc(1:z-1) = 0;      nextc(z) = 1;        %// make the first zero a one      nextc(1:nnz(oldc(1:z-2))) = 1;  %// move previous ones to the beginning   else      nextc = zeros(size(oldc));      nextc(1:nnz(oldc)) = 1;         %// start over   endend

(请注意,

else
只有在您希望组合从最后一个组合绕到第一个组合时,该子句才是必需的。)

如果使用以下方式调用此函数:

A = [1 1 1 1 1 0 1 0 0 1 1]nextCombination = nextComb(A)

输出将是:

A =   1   1   1   1   1   0   1   0   0   1   1nextCombination =   1   1   1   1   0   1   1   0   0   1   1

然后,您可以将其用作字母(或想要组合的任何元素)的蒙版。

C = ['a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k']C(find(nextCombination))ans = abcdegjk

此顺序中的第一个组合是

1   1   1   1   1   1   1   1   0   0   0

最后是

0   0   0   1   1   1   1   1   1   1   1

要以编程方式生成第一个组合,

n = 11; k = 8;nextCombination = zeros(1,n);nextCombination(1:k) = 1;

现在,您可以遍历组合(或者您愿意等待的数目):

for c = 2:nchoosek(n,k)   %// start from 2; we already have 1   nextCombination = nextComb(A);   %// do something with the combination...end

对于上面的示例:

nextCombination = [1 1 0];C(find(nextCombination))for c = 2:nchoosek(3,2)   nextCombination = nextComb(nextCombination);   C(find(nextCombination))endans = abans = acans = bc

注意:
我已经更新了代码;我忘了包括将所有在交换的数字之前出现的1移到数组开头的行。当前代码(除了上面已更正的代码)在此处为ideone
。输出为

4 choose 2


allCombs =   1   2   1   3   2   3   1   4   2   4   3   4


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/427652.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号