powerset {1, 2, 3}是:
{{}, {2}, {3}, {2, 3}, {1, 2}, {1, 3}, {1, 2, 3}, {1}}
假设我有一个SetJava语言:
Set<Integer> mySet = new HashSet<Integer>();
mySet.add(1);
mySet.add(2);
mySet.add(3);
Set<Set<Integer>> powerSet = getPowerset(mySet);
Run Code Online (Sandbox Code Playgroud)
如何以最佳的复杂度顺序编写函数getPowerset?(我想它可能是O(2 ^ n).)
我正在尝试获取与输入 arrayList 长度相同的 ArrayList 的所有可能排列。即 1,2,3 的 ArrayList 将导致 123, 132, 213, 231, 321, 312,不包括更短的排列,如 1, 2, 12, 13 ... 等等。这是我到目前为止的代码:
public void getAllPermutations(ArrayList<coordinate> coords) {
ArrayList<coordinate> sub = new ArrayList<coordinate>();
permutateSub(sub, coords);
}
private ArrayList<ArrayList<coordinate>> permutateSub(ArrayList<coordinate> sub,
ArrayList<coordinate> coords) {
int n = coords.size();
if(n == 0) System.out.println(sub);
else {
if(sub.size()==n) {
System.out.println(sub);
for(int i = 0; i<n; i++) {
ArrayList<coordinate> a = new ArrayList<coordinate>(sub);
a.add(coords.get(i));
ArrayList<coordinate> b = new ArrayList<coordinate>(coords);
b.remove(i);
permutateSub(a, b);
}
}
}
Run Code Online (Sandbox Code Playgroud)
坐标是一个类,它只有 x、y …