字符串的排列組合
描述
輸入一個字符串,按字典序打印出該字符串中字符的所有排列。例如輸入字符串abc,則打印出由字符a,b,c所能排列出來的所有字符串abc,acb,bac,bca,cab和cba。 結果請按字母順序輸出。 (輸入一個字符串,長度不超過9(可能有字符重複),字符只包括大小寫字母。)
分析
i個字母的排列組合和i+1個字母的排列組合問題近乎一致,所以可以通過遞歸來解決。同時i個字母的排列組合和i+1個字母排列之間又存在關係,通過回溯法列舉出所有方式,然後通過Set結構體的特性去重,再按照字母順序排列
代碼
private boolean[] has;
private char[] result;
private HashSet<String> set = new HashSet<String>();
//DFS
private void fillChar(char[] chars, int n) {
if (n >= chars.length) {
set.add(new String(result));
return;
}
for (int i = 0; i < chars.length; i++) {
if (!has[i]) {
result[n] = chars[i];
has[i] = true;
fillChar(chars, n + 1);
has[i] = false;
}
}
}
public ArrayList<String> Permutation(String str) {
ArrayList<String> list = new ArrayList<String>();
int length = str.length();
if (str == null || length == 0) {
return list;
}
has = new boolean[length];
result = new char[length];
char[] chars = str.toCharArray();
fillChar(chars, 0);
list.addAll(set);
Collections.sort(list);
return list;
}
測試
public void testPermutation() {
assertEquals(6, solution.Permutation("abc").size());
}
八皇后問題
描述
分析
從第一行開始,i表示行數,j表示列數(1<=i,j<=8)
- 第1行 j的位置可爲任意
- 第2行 j的位置取決第1行
- 第3行 j的位置取決於第1和第2行
- 第i行的可擺放位置,取決於i-1行的棋子擺放
由此可以遞歸處理。然後再逐行遍歷循環
代碼
// 8行8列
public final static int MAX = 8;
/** 存儲總共有多少種解法 */
public static int count = 0;
// 從1開始計數,存儲1表示這個位置是一個合法位置,0表示不是一個合法位置。因爲種解法每一行只有一個1,第0列用來存儲只有一個1的座標位置
private int[][] matrix = new int[MAX + 1][MAX + 1];
/**
* 判斷座標(i,j)是不是一個可用位置
*/
public boolean isLegal(int j, int i) {
for (int m = 1; m < j; m++) {
int n = matrix[m][0];
if (n == i || Math.abs(i - n) == Math.abs(j - m)) {
return false;
}
}
return true;
}
/**
* 打印解法
*/
public void printMatrix() {
count++;
System.out.println("NO." + count);
for (int i = 1; i <= MAX; i++) {
for (int j = 1; j <= MAX; j++) {
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}
}
/**
* 填充棋子
*/
public void fill(int i) {
if (i > MAX) {
printMatrix();
} else {
for (int m = 1; m <= MAX; m++) {
matrix[i][m] = 1;
if (isLegal(i, m)) {
matrix[i][0] = m;
fill(i + 1);
}
matrix[i][m] = 0;
}
}
}
測試
public void testFill() {
// 打印
solution.fill(1);
}