从m中选择n个元素

import java.util.ArrayList;
import java.util.List;

public class PickingATeam {

public static void main(String[] args) {
PickingATeam pick = new PickingATeam();
List<String> ls = new ArrayList<String>();
ls.add("A");
ls.add("B");
ls.add("C");
ls.add("D");
// ls.add("E");
// ls.add("F");
// ls.add("G");
// ls.add("H");
// ls.add("I");
// ls.add("J");

String[] s = ls.toArray(new String[4]);

s = pick.pick(s, 0, ls.size(), 4);
for (int i = 0; i < s.length; i++) {
System.out.println(s[i]);
}
}

public String[] pick(String[] ls, int start, int end, int teamNum) {

// if the number you found is smaller than 0 ,it is invalid.
// if the number you found is bigger than the length of collection.
// invalidate!
if (teamNum < 1 || teamNum > (end - start)) {
return new String[0];
}
// if teamNum is 1, all the elements will be returned.
if (teamNum == 1) {
String[] candidate = new String[end - start];
for (int i = 0; i < candidate.length; i++) {
candidate[i] = ls[start + i];
}
return candidate;
}
// (n, k) = (n – 1, k – 1) + (n – 1, k);

// in the first part, only n-1 elements will be used. the n element will
// combin will the (n – 1, k – 1)result.

// this is that n element which is not included when picking the team.
String FirstElem = ls[start];
// getting (n-1,k-1);and combin with element n;
String[] firPart = combin(FirstElem,
pick(ls, start + 1, end, teamNum - 1));

// getting (n – 1, k);
String[] secondPart = pick(ls, start + 1, end, teamNum);

// code below are used to merge the result.
int fristPartLength = firPart.length;
int secondPartLength = secondPart.length;

String[] pickingResult = new String[fristPartLength + secondPartLength];

for (int i = 0; i < fristPartLength + secondPartLength; i++) {
if (i < fristPartLength) {
pickingResult[i] = firPart[i];
} else {
pickingResult[i] = secondPart[i - fristPartLength];
}

}

return pickingResult;
}

/**
* combin(a,[b,c,d]); return[ab,ac,ad]
* */

private String[] combin(String elem, String[] all) {
String[] local = new String[all.length];
for (int i = 0; i < all.length; i++) {
local[i] = all[i];
}
for (int i = 0; i < local.length; i++) {
local[i] = elem + local[i];
}
return local;
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值