[关闭]
@XQF 2018-03-07T23:00:07.000000Z 字数 1897 阅读 846

如何输出字符串的所有组合?

数据结构与算法


题目描述:假如字符串中的字符都不重复,如何输出字符串的所有组合?例如“abc”
---->a,b,c,ab,bc,ac,abc

1.首发--老办法

其实就是深搜的过程中的所有情况,。注意去重

还有一点就是,。,。这个set莫名奇妙被套了一层,后面再来重构

  1. public class Solution {
  2. private Set<String> resultSet = new HashSet<>();
  3. public void printAllCombination(String string) {
  4. if (string == null || string.length() == 0) {
  5. return;
  6. }
  7. char[] chars = string.toCharArray();
  8. StringBuffer sb = new StringBuffer();
  9. int step = 0;
  10. int[] book = new int[string.length()];
  11. dfs(chars, sb, book, step);
  12. System.out.println(resultSet);
  13. for (String str : resultSet) {
  14. if (str.equals("[]")) {
  15. continue;
  16. } else {
  17. System.out.println("result:" + str.substring(1, str.length()-1));
  18. }
  19. }
  20. }
  21. public void dfs(char[] chars, StringBuffer sb, int[] book, int step) {
  22. char[] resultChar = sb.toString().toCharArray();
  23. Arrays.sort(resultChar);
  24. String resultString = Arrays.toString(resultChar);
  25. if (resultString != null && resultString.length() != 0) {
  26. resultSet.add(resultString);
  27. }
  28. if (step == book.length) {
  29. return;
  30. }
  31. for (int i = 0; i < chars.length; i++) {
  32. if (book[i] == 0) {
  33. book[i] = 1;
  34. sb.append(chars[i]);
  35. dfs(chars, sb, book, step + 1);
  36. book[i] = 0;
  37. sb.deleteCharAt(sb.length() - 1);
  38. }
  39. }
  40. }
  41. public static void main(String[] args) {
  42. Solution solution = new Solution();
  43. String string = "abc";
  44. solution.printAllCombination(string);
  45. }
  46. }

2.,。,有玄妙

根据排列组合知识,,结果应为个元素,。,恰好对应
1,10,11,100,。,。
1到len的数的二进制表示的1的位置,,。
太有意思了,。,哈哈

  1. public class Solution {
  2. public void printAllCombination(String string) {
  3. if (string == null || string.length() == 0) {
  4. return;
  5. }
  6. char[] chars = string.toCharArray();
  7. int len = string.length();
  8. long end = (int) (Math.pow(2, len) - 1);
  9. for (int i = 1; i <= end; i++) {
  10. StringBuffer sb = new StringBuffer();
  11. String tempString = Integer.toBinaryString(i);
  12. while (tempString.length() < len) {
  13. tempString = "0" + tempString;
  14. }
  15. char[] tempChars = tempString.toCharArray();
  16. for (int j = 0; j < tempChars.length; j++) {
  17. if (tempChars[j] == '1') {
  18. sb.append(chars[j]);
  19. }
  20. }
  21. System.out.println("result:" + sb.toString());
  22. }
  23. }
  24. public static void main(String[] args) {
  25. Solution solution = new Solution();
  26. String string = "abc";
  27. solution.printAllCombination(string);
  28. }
  29. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注