java求任意个数集合的笛卡尔积,如何在Java中的任意数字组上创建笛卡尔积?

Let's say I have 2 groups of numbers:

{1, 2, 3},

{4, 5}

I'd like to create an algorithm (in Java) that outputs the following 6 combinations:

1,4

1,5

2,4

2,5

3,4

3,5

There can be an arbitrary number of groups and an arbitrary number of members within each group. So in the above example, there are 2 groups with the first group having 3 members and the second group having 2 members. Another example is the following (3 groups, 3 members in first groups and 2 members in second and third groups):

{1, 2, 3},

{4, 5},

{6, 7}

Which would yield the following 12 combinations:

1,4,6

1,4,7

1,5,6

1,5,7

2,4,6

2,4,7

2,5,6

2,5,7

3,4,6

3,4,7

3,5,6

3,5,7

How can I do this in Java? I'm trying to use recursion and I've looked at a similar question already but I'm still coming up short. Thanks for the help! (P.S. this is not for a homework assignment)

解决方案

Got a bit bored and decided to give it a shot. Should be exactly what you need:

public static void main(String args[]) {

ArrayList input = new ArrayList();

input.add(new int[] { 1, 2, 3 });

input.add(new int[] { 4, 5 });

input.add(new int[] { 6, 7 });

combine(input, new int[input.size()], 0);

}

private static void combine(ArrayList input, int[] current, int k) {

if(k == input.size()) {

for(int i = 0; i < k; i++) {

System.out.print(current[i] + " ");

}

System.out.println();

} else {

for(int j = 0; j < input.get(k).length; j++) {

current[k] = input.get(k)[j];

combine(input, current, k + 1);

}

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值