用1、2、3、3、4、5这六个数字,用java写一个程序,打印出所有不同的排列 要求:"4"不能在第三位,"3"与"5"不能相连。
用1、2、3、3、4、5这六个数字,用java写一个程序,打印出所有不同的排列 要求:"4"不能在第三位,"3"与"5"不能相连。
递归:
import java.util.ArrayList;
import java.util.List;
public class Test1 {
public static void f(String in, ArrayList al) {
if (al.size() == 1) {
String tmp = in ;
if (!(tmp.contains("35") || tmp.contains("53") || tmp.indexOf('4') == 2)) {
System.out.println(tmp);
}
} else {
ArrayList hsc = (ArrayList) al.clone();
if (in.length() != 0) {
hsc.remove(in.substring(in.length() - 1));
}
for (Object i : hsc) {
f(in + i, hsc);
}
}
}
public static void ff(String in, ArrayList al){
if (al.size()==1) {
if (!(in.contains("35")||in.contains("53")||in.indexOf("4")==2)) {
System.out.println(in);
}
} else {
ArrayList hsc=(ArrayList) al.clone();
if (in.length()!=0) {
hsc.remove(in.substring(in.length()-1));
}
for (String string : hsc) {
ff(in+string,hsc);
}
}
}
public static void main(String args[]) {
ArrayList al = new ArrayList();
al.add("1");
al.add("2");
al.add("3");
al.add("4");
al.add("5");
al.add("6");
f("", al);
}
}
循环遍历:
import java.util.ArrayList;
public class Test2 {
public static void main(String args[]) {
int[] nums = { 1, 2, 2, 3, 4, 5 };
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
if (i == j || (nums[i] * nums[j] == 15))
continue;
for (int k = 0; k < nums.length; k++) {
if (k == i || k == j || (nums[j] * nums[k] == 15)
|| nums[k] == 4) {
continue;
}
for (int m = 0; m < nums.length; m++) {
if (m == k || m == i || m == j
|| (nums[k] * nums[m] == 15)) {
continue;
}
for (int n = 0; n < nums.length; n++) {
if (n == m || n == k || n == i || n == j
|| (nums[m] * nums[n] == 15)) {
continue;
}
for (int l = 0; l < nums.length; l++) {
if (l == n || l == m || l == k || l == j
|| l == i || (nums[n] * nums[l] == 15)) {
continue;
}
System.out.println(nums[i] + "" + nums[j] + ""
+ nums[k] + "" + nums[m] + "" + nums[n]
+ "" + nums[l]);
}
}
}
}
}
}
}
}