开发者社区> 问答> 正文

Java算法 排序问题

有1,2,3,4四个数,用java代码实现1234,1342这样的没有重复的组合。

展开
收起
知与谁同 2018-07-21 11:38:44 1603 0
1 条回答
写回答
取消 提交回答
  • Nothing for nothing.
    用到了Enumeration,代码如下:

    import java.util.Enumeration;

    /**
    * N个要素序列生成,个数为N!
    */
    public class PermEnum implements Enumeration {

    private int n;
    private int c[], k;
    private Object[] objs;

    public PermEnum(Object[] items) {
    n = items.length;
    c = new int[n + 1];
    for (int i = 0; i <= n; i++) {
    c[i] = i;
    }
    objs = items;
    k = 1;
    }

    public boolean hasMoreElements() {
    return k < n;
    }

    public Object nextElement() {
    int i = 0;
    if ((k & 1) != 0) {
    i = c[k];
    }
    Object tmp = objs[k];
    objs[k] = objs[i];
    objs[i] = tmp;

    k = 1;
    while (c[k] == 0) {
    c[k] = k++;
    }
    c[k]--;
    return objs;
    }

    // TEST输出
    public static void main(String[] args) {
    String[] strs = {"1", "2", "3", "4"}; // 这里可以自己定义
    System.out.println("N=" + strs.length);
    Enumeration e = new PermEnum(strs);
    int count = 0;
    while (e.hasMoreElements()) {
    String[] a = (String[]) e.nextElement();
    System.out.print("[" + a[0]);
    for (int i = 1; i < a.length; i++)
    System.out.print(", " + a[i]);
    System.out.println("]");
    count++;
    }
    System.out.println("count=" + count);
    }

    }
    2019-07-17 22:50:19
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载