经典面试题解答

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

用1、2、2、3、4、5这六个数字,用java写一个main函数,打印出所有不同的排列,如:512234、412345等,要求:"4"不能在第三位,"3"与"5"不能相连。
package test1;

import java.util.ArrayList;
import java.util.List;

public class TestList2 {
	//用1、2、2、3、4、5这六个数字,用java写一个main函数,打印出所有不同的排列,如:512234、412345等,要求:"4"不能在第三位,"3"与"5"不能相连。
	public static void main(String[] args) {
		List<String> l = new ArrayList<String>();
		l.add("1");l.add("2");l.add("2");l.add("3");l.add("4");l.add("5");
		List<String> l1 = new ArrayList<String>();
		List<String> l2 = new ArrayList<String>();
		List<String> l3 = new ArrayList<String>();
		List<String> l4 = new ArrayList<String>();
		List<String> l5 = new ArrayList<String>();
		List<String> rel = new ArrayList<String>();
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < l.size(); i++) {
			sb.append(l.get(i));
			String n1 = l.remove(i);
			l1 = l;
			for (int j = 0; j < l1.size(); j++) {
				sb.append(l1.get(j));
				String n2 = l1.remove(j);
				l2 = l1;
				for (int j2 = 0; j2 < l2.size(); j2++) {
					sb.append(l2.get(j2));
					String n3 = l2.remove(j2);
					l3 = l2;
					for (int k = 0; k < l3.size(); k++) {
						sb.append(l3.get(k));
						String n4 = l3.remove(k);
						l4 = l3;
						for (int k2 = 0; k2 < l4.size(); k2++) {
							sb.append(l4.get(k2));
							String n5 = l4.remove(k2);
							l5 = l4;
							for (int m = 0; m < l5.size(); m++) {
								sb.append(l.get(m));
								String n6 = l5.remove(m);
								System.out.println(sb.toString());
								if (!rel.contains(sb.toString()) && sb.toString().indexOf("4")!=2 && !sb.toString().contains("35") && !sb.toString().contains("53")) {
									rel.add(sb.toString());
								}
								sb.delete(sb.length()-1, sb.length());
								l5.add(m, n6);
							}
							sb.delete(sb.length()-1, sb.length());
							l4.add(k2, n5);
						}
						sb.delete(sb.length()-1, sb.length());
						l3.add(k, n4);
					}
					sb.delete(sb.length()-1, sb.length());
					l2.add(j2, n3);
				}
				sb.delete(sb.length()-1, sb.length());
				l1.add(j, n2);
			}
			sb.delete(sb.length()-1, sb.length());
			l.add(i, n1);
		}
		System.out.println(rel.size());
		System.out.println(rel.toString());
	}
	

}