- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 64 lines of C++ from the credited upstream file number-of-integers-with-popcount-depth-equal-to-k-i.cpp.
- The implementation visibly relies on sequence storage.
- 5 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1234 56int bit_length(int64_t x) {7 return (x ? std::__lg(x) : -1) + 1;8}9 10pair<vector<vector<int64_t>>, vector<int>> init() {11 static const int64_t MAX_N = 1e15;12 static const int MAX_BIT_LEN = bit_length(MAX_N);13 vector<vector<int64_t>> NCR(MAX_BIT_LEN + 1, vector<int64_t>(MAX_BIT_LEN + 1));14 for (int i = 0; i < size(NCR); ++i) {15 for (int j = 0; j <= i; ++j) {16 NCR[i][j] = 0 < j && j < i ? NCR[i - 1][j] + NCR[i - 1][j - 1] : 1;17 }18 }19 vector<int> D(MAX_BIT_LEN + 1, 0);20 for (int i = 2; i < size(D); ++i) {21 D[i] = D[__builtin_popcount(i)] + 1;22 }23 return {NCR, D};24}25 26const auto& [NCR, D] = init();27class Solution {28public:29 long long popcountDepth(long long n, int k) {30 if (k == 0) {31 return 1;32 }33 const int l = bit_length(n);34 if (k == 1) {35 return l - 1;36 }37 const auto& count = [&](int c) {38 int64_t result = 0;39 int cnt = 0;40 for (int i = l - 1; i >= 0; --i) {41 if (!(n & (1ll << i))) {42 continue;43 }44 if (0 <= c - cnt && c - cnt <= i) {45 result += NCR[i][c - cnt];46 }47 ++cnt;48 }49 if (cnt == c) {50 ++result;51 }52 return result;53 };54 55 int64_t result = 0;56 for (int c = 2; c <= l; ++c) {57 if (D[c] == k - 1) {58 result += count(c);59 }60 }61 return result;62 }63};64