@XQF
2018-03-07T23:00:07.000000Z
字数 1897
阅读 846
数据结构与算法
题目描述:假如字符串中的字符都不重复,如何输出字符串的所有组合?例如“abc”
---->a,b,c,ab,bc,ac,abc
其实就是深搜的过程中的所有情况,。注意去重
还有一点就是,。,。这个set莫名奇妙被套了一层,后面再来重构
public class Solution {
private Set<String> resultSet = new HashSet<>();
public void printAllCombination(String string) {
if (string == null || string.length() == 0) {
return;
}
char[] chars = string.toCharArray();
StringBuffer sb = new StringBuffer();
int step = 0;
int[] book = new int[string.length()];
dfs(chars, sb, book, step);
System.out.println(resultSet);
for (String str : resultSet) {
if (str.equals("[]")) {
continue;
} else {
System.out.println("result:" + str.substring(1, str.length()-1));
}
}
}
public void dfs(char[] chars, StringBuffer sb, int[] book, int step) {
char[] resultChar = sb.toString().toCharArray();
Arrays.sort(resultChar);
String resultString = Arrays.toString(resultChar);
if (resultString != null && resultString.length() != 0) {
resultSet.add(resultString);
}
if (step == book.length) {
return;
}
for (int i = 0; i < chars.length; i++) {
if (book[i] == 0) {
book[i] = 1;
sb.append(chars[i]);
dfs(chars, sb, book, step + 1);
book[i] = 0;
sb.deleteCharAt(sb.length() - 1);
}
}
}
public static void main(String[] args) {
Solution solution = new Solution();
String string = "abc";
solution.printAllCombination(string);
}
}
根据排列组合知识,,结果应为个元素,。,恰好对应
1,10,11,100,。,。
1到len的数的二进制表示的1的位置,,。
太有意思了,。,哈哈
public class Solution {
public void printAllCombination(String string) {
if (string == null || string.length() == 0) {
return;
}
char[] chars = string.toCharArray();
int len = string.length();
long end = (int) (Math.pow(2, len) - 1);
for (int i = 1; i <= end; i++) {
StringBuffer sb = new StringBuffer();
String tempString = Integer.toBinaryString(i);
while (tempString.length() < len) {
tempString = "0" + tempString;
}
char[] tempChars = tempString.toCharArray();
for (int j = 0; j < tempChars.length; j++) {
if (tempChars[j] == '1') {
sb.append(chars[j]);
}
}
System.out.println("result:" + sb.toString());
}
}
public static void main(String[] args) {
Solution solution = new Solution();
String string = "abc";
solution.printAllCombination(string);
}
}