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

生成字符串排列和组合的智能方法

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

生成字符串排列和组合的智能方法

您应该检查以下答案:在Java中获取字符串或组合的所有可能排列,包括重复的字符

要获取此代码:

public static String[] getAllLists(String[] elements, int lengthOfList){    //lists of length 1 are just the original elements    if(lengthOfList == 1) return elements;     else {        //initialize our returned list with the number of elements calculated above        String[] allLists = new String[(int)Math.pow(elements.length, lengthOfList)];        //the recursion--get all lists of length 3, length 2, all the way up to 1        String[] allSublists = getAllLists(elements, lengthOfList - 1);        //append the sublists to each element        int arrayIndex = 0;        for(int i = 0; i < elements.length; i++){ for(int j = 0; j < allSublists.length; j++){     //add the newly appended combination to the list     allLists[arrayIndex] = elements[i] + allSublists[j];     arrayIndex++; }        }        return allLists;    }}public static void main(String[] args){    String[] database = {"a","b","c"};    for(int i=1; i<=database.length; i++){        String[] result = getAllLists(database, i);        for(int j=0; j<result.length; j++){ System.out.println(result[j]);        }    }}

尽管可以对内存进行进一步的改进,但是由于此解决方案首先生成了所有内存解决方案(数组),然后才能进行打印。但是想法是一样的,那就是使用递归算法。



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

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

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