一著名软件公司的java笔试算法题!
算法程序题:
该公司笔试题就1个,要求在10分钟内作完。
题目如下:用1、2、2、3、4、5这六个数字,用java写一个main函数,打印出所有不同的排列,如:512234、412345等,要求:"4"不能在第三位,"3"与"5"不能相连。
循环方法
class Test2 {
public static void main(String args[]) {
char[] c = { '1', '2', '2', '3', '4', '5' };
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < c.length; j++) {
if (i == j || (c[i] == '3' && c[j] == '5'))
continue;
for (int k = 0; k < c.length; k++) {
if (k == i || k == j || (c[j] == '3' && c[k] == '5')
|| c[k] == '4') {
continue;
}
for (int m = 0; m < c.length; m++) {
if (m == k || m == i || m == j
|| (c[k] == '3' && c[m] == 5)) {
continue;
}
for (int n = 0; n < c.length; n++) {
if (n == m || n == k || n == i || n == j
|| (c[m] == '3' && c[n] == '5')) {
continue;
}
for (int l = 0; l < c.length; l++) {
if (l == n || l == m || l == k || l == j
|| l == i
|| (c[n] == '3' && c[l] == '5')) {
continue;
}
System.out.println(c[i] + "" + c[j] + "" + c[k]
+ "" + c[m] + "" + c[n] + "" + c[l]);
}
}
}
}
}
}
}
}
递归方法
class Test2 {
public int[] getNextDifPos(int[] before, int add) {
int[] res = new int[before.length + 1];
for (int i = 0; i < before.length; i++) {
res[i] = before[i];
}
res[res.length - 1] = add;
return res;
}
public int getNextPos(int[] pos) {
for (int i = 0; i < pos.length; i++) {
if (pos[i] != -1) {
return i;
}
}
return -1;
}
public void getStr(int[] before, char[] chars) {
if (before.length == chars.length) {
StringBuffer str = new StringBuffer();
for (int i = 0; i < before.length; i++) {
str.append(chars[before[i]]);
}
// 加判断条件
if (str.charAt(2) == '4' || str.indexOf("35") >= 0) {
return;
}
System.out.println(str.toString());
} else if (before.length < chars.length) {
int[] pos = new int[chars.length];
for (int i = 0; i < before.length; i++) {
pos[before[i]] = -1;
}
int nextPos;
while ((nextPos = getNextPos(pos)) != -1) {
pos[nextPos] = -1;
getStr(getNextDifPos(before, nextPos), chars);
}
}
}
public static void main(String args[]) {
char[] c = { '1', '2', '2', '3', '4', '5' };
int[] l = {};
Test2 t = new Test2();
t.getStr(l, c);
}
}
</script>