有一个没有重复的集合 是,求S的所有子集,按生序排序,不能重复,用java
时间: 2024-10-28 10:10:07 浏览: 14
java一亿数字取前100个(3秒钟获取)
在Java中,你可以使用递归和HashSet来生成并存储所有非重复的子集。这里是一个简单的示例:
```java
import java.util.*;
public class Subsets {
private Set<List<Integer>> subsets;
public Subsets(int[] nums) {
this.subsets = new HashSet<>();
generateSubsets(nums, new ArrayList<>(), 0);
}
private void generateSubsets(int[] nums, List<Integer> currentSet, int index) {
// Base case: when the index reaches the length of array, add current set to result
if (index == nums.length) {
subsets.add(new ArrayList<>(currentSet));
return;
}
// Include the element at the current index
currentSet.add(nums[index]);
generateSubsets(nums, currentSet, index + 1);
// Exclude the element and move forward
currentSet.remove(currentSet.size() - 1);
generateSubsets(nums, currentSet, index + 1);
}
public List<List<Integer>> getSortedSubsets() {
List<List<Integer>> sortedSubsets = new ArrayList<>(subsets);
Collections.sort(sortedSubsets, Comparator.comparingInt(List::size)); // Sort by set size first, then lexicographically
return sortedSubsets;
}
public static void main(String[] args) {
int[] nums = {1, 2, 3};
Subsets subsetGenerator = new Subsets(nums);
System.out.println(subsetGenerator.getSortedSubsets());
}
}
```
这个程序首先创建了一个空的HashSet来收集所有子集。然后通过递归地包含或排除数组中的元素,生成所有的子集。最后,将子集列表按照大小和元素升序排序。
阅读全文