`

N!的全排列算法(Java实现)

    博客分类:
  • JAVA
阅读更多
public class TestSort {
    String[] list;
    StringBuffer sb;
    int len, start;

    TestSort(String in) {
        len = Integer.parseInt(in);
        list = new String[len];
        for (int i = 0; i < len; i++) list[i] = String.valueOf(i + 1);
        permutation(0,len-1);
    }

    void swap(int c1, int c2) {
        String temp = list[c1];
        list[c1] = list[c2];
        list[c2] = temp;
    }

    void permutation(int m,int n) {
        if (m==n) {
            sb = new StringBuffer();
            for (int i = 0; i < len; i++) sb.append(list[i]);
            sb.append(" ");
            System.out.print(sb);
        } else {
            for (int i = m; i<=n; i++) {
                swap(m, i);//交换
                permutation(m+1,n);
                swap(m,i);//还原
            }
        }
    }

    public static void main(String args[]) {
        new TestSort("3");
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics