给定一个长度和字符集,如何得到所有可能的字符串组合

编程入门 行业动态 更新时间:2024-10-08 10:50:06
本文介绍了给定一个长度和字符集,如何得到所有可能的字符串组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复:   Generating对一个给定的字符串所有排列

Possible Duplicate: Generating all permutations of a given string

由于长度 N = 4, 和字符集 - > {'A','B'} , 如何编写一些Java codeS产生所有可能的字符串包含在设定的字符长度为n?

Given a length n=4, and a set of characters -> {'a', 'b'}, how to write some java codes to produce all the possible string with that length n containing the characters in the set?

有关上面的例子中,结果应具有2 ^ 4 = 16字符串,它是:

For the example above, the result should have 2^4=16 strings, which is:

aaaa aaab aabb abbb baaa baab babb bbbb bbaa bbab bbba abaa abab abba baba aaba

这是我的code片断:

here is my code snippet:

public void process(String result, String string) { if(string.length() == 0) { System.out.println(result); }else{ for(int i = 0; i < string.length(); i++) { String newResult = new String(result+string.charAt(i)); String newString = new String(string.substring(0,i) + string.substring(i+1, string.length())); process(newResult, newString); } } }

这似乎只是在做什么,而不是我想要的排列,....... 预先感谢您:)

That seems like only doing permutation, instead of what I want....... Thank you in advance :)

推荐答案

把它以同样的方式将计数。你专门从AAAA计数到BBBB,像二进制。

Think of it in the same way you would counting. You're technically "counting" from aaaa to bbbb, like binary.

aaaa -> 0000 aaab -> 0001 aaba -> 0010 aabb -> 0011 ... bbbb -> 1111

没有看到你已经试过,我不能帮你不止于此,但本质上则需要通过它们计数列举你的最低的元素,你的最高元素之间的所有的数字。

Without seeing what you've tried, I can't help you more than that, but essentially you need to enumerate all the "numbers" between your "lowest" element and your "highest" element by counting up through them.

对于更高的元件数量,只是把你计算在基数较高计数。对于八素,集= {A,B,C,D,E,F,G,H},你会被计算在什么本质八:

For higher element counts, just treat your counting as counting in a higher base. For eight elements, Set = {a, b, c, d, e, f, g, h}, you would be counting up in what's essentially octal:

aaaa -> 0000 aaab -> 0001 ... aaah -> 0007 aaba -> 0010 ... hhhh -> 7777

这是你列举的0-9所有组合,带4的长度,从0000计数到9999相同的方式。

It's the same way you enumerate all the combinations of 0-9 with a length of 4, by counting from 0000 to 9999.

编辑:

感谢您发布您的code。你是正确的,你在做排列组合。更好的方法是使用多组合(组合在进排序组合组重复的元素)算法,像一个讨论的这里。

Thank you for posting your code. You're correct, you're doing permutations. A better way would be to use a multi-combination (combination with repeated elements in the ordererd combination set) algorithm like the one discussed here.

更多推荐

给定一个长度和字符集,如何得到所有可能的字符串组合

本文发布于:2023-11-30 07:31:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649179.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   字符集   字符串   长度

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!