classSolution { public: intminKBitFlips(vector<int>& a, int K){ int ret = 0; int cur = 0; while (cur < a.size()) { if (a[cur] == 0) { ret++; for (int j = 0; j < K; j++) { if (cur + j >= a.size()) return-1; a[cur + j] = 1 - a[cur + j]; } } cur++; } return ret; } };
996. Number of Squareful Arrays
自己写了个复杂的C++ dfs,结果TLE,还把自己搞晕了...
后来看别人写的巨简单...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: defnumSquarefulPerms(self, A: 'List[int]') -> 'int': c = collections.Counter(A) cand = {i: {j for j in c ifint(((i + j) ** 0.5)) ** 2 == i + j} for i in c} self.res = 0 defdfs(x, left=len(A) - 1): c[x] -= 1 if left == 0: self.res += 1 for y in cand[x]: if c[y]: dfs(y, left - 1) c[x] += 1 for x in c: dfs(x) return self.res