java - 控制幂集中元素的顺序

标签 java

我有这段代码可以为一组给定的元素生成幂集。在示例中,我的元素是 1、2 和 3。所以这会生成...

{1}、{2}、{3}、{1、2}、{1、3}、{2、3}、{1、2、3}

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

public class test {
    static List<List<Integer>> powerSet;

    public static void main(String[] args) {
        powerSet = getPowerSet(new ArrayList<Integer>() {
            {
                add(1);
                add(2);
                add(3);
            }
        });
        for (List<Integer> i : powerSet) {
            for (Integer i2 : i) {
                System.out.print(i2 + " ");
            }
            System.out.println();
        }
    }

    private static List<List<Integer>> getPowerSet(List<Integer> itemList) {
        List<List<Integer>> ps = new ArrayList<List<Integer>>();
        ps.add(new ArrayList<Integer>()); // add the empty set

        // for every item in the original list
        for (Integer i : itemList) {
            List<List<Integer>> newPs = new ArrayList<List<Integer>>();

            for (List<Integer> subset : ps) {
                // copy all of the current powerset's subsets
                newPs.add(subset);

                // plus the subsets appended with the current item
                List<Integer> newSubset = new ArrayList<Integer>(subset);
                newSubset.add(i);
                newPs.add(newSubset);
            }

            // powerset is now powerset of list.subList(0, list.indexOf(item)+1)
            ps = newPs;
        }
        ps.remove(0); // remove the emptyset
        return ps;
    }
}

问题是,我的结果没有排序,这是我得到的结果。

3 
2 
2 3 
1 
1 3 
1 2 
1 2 3 

我想得到:

1 
2 
3  
1 2
1 3 
2 3 
1 2 3 

最佳答案

您可以使用 Collections.sort 对它们进行排序,其中包含一些排序逻辑,首先检查它的长度(如果它们彼此相等)并将其解析为 int。但是您需要先将数字列表存储到一个字符串中,以便您可以检查整数的长度和精度。

示例:

Collections.sort(powerSet, new Comparator<List<Integer>>() {

        @Override
        public int compare(List<Integer> o1, List<Integer> o2) {
            StringBuilder temp = new StringBuilder();
            StringBuilder temp2 = new StringBuilder();
            for (Integer i2 : o1) {
                temp.append( i2 );
            }
            for (Integer i2 : o2) {
                temp2.append( i2 );
            }

            if(temp.length() == temp2.length())
                return Integer.parseInt(temp.toString()) - Integer.parseInt(temp2.toString());
            else
                return temp.length() - temp2.length();
        }
    });

结果:

1 
2 
3 
1 2 
1 3 
2 3 
1 2 3 

关于java - 控制幂集中元素的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25196131/

相关文章:

java - 想要在使用 GridView 时更新 getView 方法

Java JSP/Servlet : how to automatically serve either a . dmg 或 .exe 文件?

java - 在抽象类中调用重写的函数

java - 关于 BroadLeaf Commerce 管理中的 GWT

java - 如果我使用 Java 将所有可能的 64 位 double 值存储在文件中,文件大小是多少?

用于数据库支持集合的 Java 库

java - 使用 Path 2d 检测坐标

java - 将 key 对转换为 RSAKey

java - 将套接字所有权移至同一 LAN 上的另一台计算机

java - 有没有办法确保将线程分配给指定的一组对象?