日期:2014-05-20 浏览次数:20892 次
char[] c = {'a','b','c','d','e','f'};
import java.util.ArrayList; import java.util.List; public class Test { public static void main(String[] args) { char[] c = {'a','b','c','d','e','f'}; //list保存找到的字符串 List<String> list = new ArrayList<String>(); //查找满足条件的字符串,并存入list for(int i=0; i<c.length; i++) { for(int j=0; j<c.length; j++) { if(i == j) continue; for(int k=0; k<c.length; k++) { if(i == k || j == k) continue; for(int l=0; l<c.length; l++) { if(i == l || j == l || k == l) continue; for(int m=0; m<c.length; m++) { if(i == m || j == m || k == m || l == m) continue; for(int n=0; n<c.length; n++) { if(i == n || j == n || k == n || l == n || m == n) continue; StringBuffer sb = new StringBuffer(); sb.append(c[i]); sb.append(c[j]); sb.append(c[k]); sb.append(c[l]); sb.append(c[m]); sb.append(c[n]); list.add(sb.toString()); } } } } } } //打印字符串的个数,换行打印字符串,每行10个 System.out.println(list.size()); int count = 0; for(int i=0; i<list.size(); i++) { System.out.print(list.get(i)); count ++; if(count % 10 != 0)//如果没够10个,行尾加","号 System.out.print(","); else//10个换行 System.out.println(); } } }
------解决方案--------------------
public static void main(String[] args) { char[] origin = { 'a', 'b', 'c', 'd', 'e', 'f' }; int length = origin.length; int[] tmp = new int[length]; char[] res = new char[length]; byte[] check = new byte[(length + 7) / 8]; int index = 0, level = 0; while (true) { if (index >= 0 && index < length && level >= 0 && level < length) { if ((check[index / 8] & (1 << index % 8)) == 0) { tmp[level] = index; res[level] = origin[index]; check[index / 8] |= (1 << index % 8); level++; index = 0; continue; } else { index++; continue; } } if (level >= length) { System.out.println(new String(res)); level = length - 1; index = tmp[level]; check[index / 8] &= ~(1 << index % 8); index++; continue; } if (index >= length) { level--; if (level < 0) break; index = tmp[level]; check[index / 8] &= ~(1 << index % 8); index++; continue; } } }
------解决方案--------------------
public static void main(String[] args) { char[] origin = { 'a', 'b', 'c', 'd', 'e', 'f' }; int length = origin.length; int[] tmp = new int[length]; char[] res = new char[length]; boolean[] check = new boolean[length]; int index = 0, level = 0; while (true) { if (index >= 0 && index < length && level >= 0 && level < length) { if (!check[index]) { tmp[level] = index; res[level] = origin[index]; check[index] = true; level++; index = 0; } else { index++; } } else if (level >= length) { System.out.println(new String(res)); level = length - 1; index = tmp[level]; check[index] = false; index++; } else if (index >= length) { level--; if (level < 0) break; index = tmp[level]; check[index] = false; index++; } else { break; } } }