本帖最后由 歌癫 于 2014-3-29 14:16 编辑
提问:给定一个字符串,如String str =“abcd”,输出它所有可能的排列组合。举例:“abcd”排列组合为>>"a","b","c","d","ab","ba","ac","ca","ad","da","bc","cb","bd","db","cd","dc","abc","acb","bac","bca","cab","cba","abd","adb","bda","bad","dab","dba","acd","adc","cda","cad","dac","dca","bcd","bdc","cdb","cbd","dbc","dcb","dabc","dacb","dbac","dbca","dcab","dcba","cabd","cadb","cbda","cbad","cdab","cdba","bacd","badc","bcda","bcad","bdac","bdca","abcd","abdc","acdb","acbd","adbc","adcb" 有这么多种排列组合。
我的分析:
1,一个字符串String str = "abcd"; 按组合长度的划分,可以分为length=str.length,就是给定的字符串多长就有多少种。
如长度为1的,"a","b"等,长度为2的,"ab","ac"等;长度为3的,"abc","acd"等;长度为4的,"abcd"等;
这是第一个难点。
2,把不同长度的字符取出来后,还要按不同顺序排列;如:”abc“,”bac“,”cba“,”acb“,”bca“,”cab“等
这是我分析的第二个难点。
解决思路:
第一个难点:
1,一个给定长度的字符串,假如长度为4,”abcd“;那么这个字符串可以取出四种不同长度的字符串;我按从长到短的顺序来取,则有
长度=4,则改字符就是它本身;
长度=3,可以理解为”abcd“,四个字符依次删除一个,然后存储到一个新的数组里;
长度=2,就是单个字符两两组合,这个可以用嵌套循环实现;
长度=1,依次取出存放到另一个数组即可;
疑问:我这是以四个长度的字符串举例,如果是长度为8呢?甚至更长呢?这里我没有找到规律。
第二个难点:还没想到怎么解决?
请教各位前辈高手,如何解决这一问题?希望可以贴出代码和必要的注释。
非常感谢~~
|