我有一个像这样的集合S[00 01 10 11]
和一个元素E作为11
。我想找出这个集合的子集的数量,其数字总和大于或等于元素E的数字总和。
例如,在这种情况下,答案是 10。满足约束的 10 个集合是:
00 01 10 11 // Sum is 3 which is greater than 2 (sum of digits of E)
00 01 11
00 10 11
01 10 11
00 11
01 11
10 11
11
00 01 10
01 10
上述子集的所有位数之和大于或等于 2(E的位数之和)。
我尝试了以下
public static void main(String[] args) {
Set<String> inputSet = new HashSet<String>();
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int M = sc.nextInt();// specifies the length of the digts in the set.
for (long i = 0 ; i < N; i++) {
inputSet.add(sc.next());
}
long sum = 0;
String E = sc.next();//
sc.close();
for (String str : E.split("(?!^)")) {
sum = sum + Integer.parseInt(str);
}
List<Set<String>> subSets = new ArrayList<Set<String>>();
for (String addToSets : inputSet) {
List<Set<String>> newSets = new ArrayList<Set<String>>();
for (Set<String> curSet : subSets) {
Set<String> copyPlusNew = new HashSet<String>();
copyPlusNew.addAll(curSet);
copyPlusNew.add(addToSets);
newSets.add(copyPlusNew);
}
Set<String> newValSet = new HashSet<String>();
newValSet.add(addToSets);
newSets.add(newValSet);
subSets.addAll(newSets);
}
long sum1;
long count = 0;
for (Set<String> set : subSets) {
sum1 = 0;
for (String setEntry : set) {
for (String s : setEntry.split("(?!^)")){
sum1 = sum1 + Integer.parseInt(s);
}
}
if (sum == sum1 || sum1 > sum)
count = count+1;
}
System.out.println(count);
}
约束 1 <= N <= 10^5
1 <= M <= 20
上述方法不适用于 10 5范围内的集合大小。请帮助为此提供一种有效的方法。谢谢!