找出所有组合和排列-Java [英] Find out all combinations and permutations - Java

查看:122
本文介绍了找出所有组合和排列-Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是这里的新手,也是初学者.我正在做一个个人项目(开发供个人使用的应用程序).我有点被困住了,是的,我确实四处搜寻,但找不到太多. 我的目的是找到所有可能的组合.假设我定义的列表数量有限,例如:

I am all new here and also a beginner. I am working on a personal project (developing an app for personal use). I am a bit stuck and yes, I did search around but couldn't find much. My aim is to find all possible combinations. Let's say I have a finite number of lists defined like:

List<String> AList contains {"a1","a2","a3","a4"} 
List<String> BList contains {"b1","b2","b3"} 
List<String> CList contains {"c1","c2","c3","c4","c5"} 
List<String> DList contains {"d1","d2"}

我想找到以下所有组合:

I would like to find all combinations with:

1)组合a1 a2静脉与a2 a1相同,依此类推

1) the combination a1 a2 vein the same as a2 a1 and so on

2)每个结果集的元素数量不固定:举例来说,一种组合可能性是将所有列表合并为一个..或列表自身中的每个元素,或合并列表中的两个元素,其余合并为另一个..依此类推.

2) the number of elements per result set not being fixed: a combination possibility is per example merging all lists into one.. or each element in a list of its own or merging two elements in a list and the rest in another.. and so on..

我知道它必须是一个递归函数.但是我现在要走多远.任何帮助将不胜感激.谢谢

I know it has to be a recursive function.. but that how far i am right now.. Any help would be appreciated. Thanks

推荐答案

我为自己做了类似的事情,但是这会给您a1 a2等的排列而不是组合,意味着顺序无关紧要.

i did a similar thing for myself, this however would give you permutations of a1 a2 etc and not combinations, meaning the order does not matter.

public void permutation(String prefix, String str) {
    int n = str.length();
    if (n==0){}
    else {
        for (int i = 0; i < n; i++)
            permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
    }

}

按照这种逻辑,您必须将列表转换成一个长字符串,然后将此方法发送给您的字符串

With this logic, you would have to turn your Lists into one long string and then send this method your string

这篇关于找出所有组合和排列-Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆