一、Problem
215
二、Solution
題意:從 22 個數中選 個數,累加其和爲 sum,要求 sum 不能在給定質數集合中找到。
方法一:BE
- 不定項選擇太麻煩了,直接枚舉子集個數吧…
- 剪枝:如果當前選擇狀態的個數超過 12 個,枚舉選擇狀態不再進行…
import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
static class Solution {
int binary_enum(int[] a) {
int res = 0, N = a.length;
int tot = 1 << N;
Set<Integer> all = new HashSet<>();
for (int i = 0; i < tot; i++) {
int cnt = 0;
int sum = 0;
for (int j = 0; j < N; j++) {
if ((i & (1 << j)) > 0) {
cnt++;
sum += a[j];
if (cnt > 12)
break;
}
}
if (cnt <= 12)
all.add(sum);
}
return 1695 - all.size();
}
void init() {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
int[] a = {3,5,7,11,13,19,23,29,31,37,41,53,59,61,67,71,97,101,127,197,211,431};
int res = binary_enum(a);
System.out.println(res);
}
}
public static void main(String[] args) throws IOException {
Solution s = new Solution();
s.init();
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,