java字符串全排列之我见。(很有成就感)

来源:互联网 发布:女朋友 知乎 编辑:程序博客网 时间:2024/05/22 05:08

看网上有关全排列算法,代码写的很复杂,自己刚好写了一个。拿出来供各位达人参考。

测试数据:

String[] source = new String[5];
  source[0] = "1";
  source[1] = "2";
  source[2] = "3";
  source[3] = "4";
  source[4] = "5";
  ArrayList result = new ArrayList();
  test.permutation(source, result);

相应代码:
public void permutation(String[] sources, List list) {
  for (int i = 0; i < sources.length; i++) {
   String permutation = sources[i];
   list.add(permutation);
   if (sources.length == 1) {
    String tmp="";
    for (int m = 0; m < list.size(); m++) {
     tmp+=list.get(m);
    }
    System.out.println(tmp);
    set.add(tmp);
    System.out.println("一组结束!");
   } else {
    String[] tmpStr = new String[sources.length - 1];
    int index = 0;
    for (int j = 0; j < sources.length; j++) {
     if (j != i) {
      tmpStr[index] = sources[j];
      index++;
     }

    }
    permutation(tmpStr, list);
   }

   list.remove(list.size() - 1);

  }

 }

希望对各位有所帮助!