[CC150] Get all permutations of a string
2014-06-06 09:34
501 查看
Problem: Compute all permutations of a string of unique characters.
此题用循环的方式不好做,下面是一种递归的思路:
![](http://images.cnitblog.com/i/358730/201406/060909341612605.jpg)
把给的字符串看成一个字符集合,每次从这个集合里拿出一个字符来填到下面的空格中。填的顺序从左到右。
把a1填到第一个空格里是一种情况,集合剩下的部分填到2-9的空格里;
把a2填到第一个空格里是一种情况,集合剩下的部分填到2-9的空格里;
。。。。。。
这样递归的进行下去,直到集合里没有剩余,所有的情况就被穷尽了。
此题用循环的方式不好做,下面是一种递归的思路:
![](http://images.cnitblog.com/i/358730/201406/060909341612605.jpg)
把给的字符串看成一个字符集合,每次从这个集合里拿出一个字符来填到下面的空格中。填的顺序从左到右。
把a1填到第一个空格里是一种情况,集合剩下的部分填到2-9的空格里;
把a2填到第一个空格里是一种情况,集合剩下的部分填到2-9的空格里;
。。。。。。
这样递归的进行下去,直到集合里没有剩余,所有的情况就被穷尽了。
public ArrayList<String> getPerms(String str){ ArrayList<String> result = new ArrayList<String>(); getPerms("", str, result); return result; } public void getPerms(String prefix, String str, ArrayList<String> result){ if(str == null || str.length() == 0){ result.add(prefix); return; } for(int i = 0; i < str.length(); ++i){ char ch = str.charAt(i); getPerms(prefix+ch, str.substring(0, i) + str.substring(i+1), result); } }
相关文章推荐
- Write a program to print all permutations of a given string
- Q9.5 Write a method to compute all permutations of a string
- Write a C program to print all permutations of a given string
- Find all the permutations of a string
- get all Palindromes of a string
- Write a method to compute all permutations of a string
- print all permutations of a given string
- How can i get hold of all of the visible items in my QListView?
- [hackerrank Value of all Permutations]
- [51nod 1309]Value of all Permutations
- UE4信息交互-GetAllActorsOfClass遍历搜索
- get content of all input tag
- Get rid of all @Override errors in Eclipse
- How To get the Real length of a string with chinese words
- How do I get the lowest value of all the non zero value pixels?
- print all permutation of a string(recursion)
- .net 中的bug:System.OutOfMemoryException At System.String.GetStringForStringBuilder
- How to get rid of `deprecated conversion from string constant to 'char*'` warnings in GCC?
- 30. Substring with Concatenation of All Words (String, Map)
- 【leetcode】String——Substring with Concatenation of All Words(30)