Problem solution · C++

Count Non Adjacent Subsets in a Rooted Tree

Count Non Adjacent Subsets in a Rooted Tree: a C++ solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Dynamic programming
Source
Kamyu LeetCode Solutions
Length
49 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Dynamic programming

For Count Non Adjacent Subsets in a Rooted Tree, the implementation records answers for smaller states and reuses them to build the requested result without repeating work.

  1. Define precisely what one DP state represents.
  2. Establish the base cases before transitions are evaluated.
  3. Process states in dependency order and combine only already-known values.

Code notes

  • 49 lines of C++ from the credited upstream file count-non-adjacent-subsets-in-a-rooted-tree.cpp.
  • The implementation visibly relies on sequence storage, cached states.
  • 6 loop blocks detected.

Complexity

Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeCount Non Adjacent Subsets in a Rooted Tree · C++C++
Use this to learn the idea, then write your own version.
// Time:  O(n * k^2)// Space: O(n * k)// if k is large, the per-merge cyclic convolution can be done in O(klogk) via NTT + CRT, Time: O(n * klogk), Space: O(n * k) in total // topological sort, tree dpclass Solution {public:    int countValidSubsets(vector<int>& parent, vector<int>& nums, int k) {        static const int MOD = 1e9 + 7;                const auto& merge = [&](const auto& a, const auto& b) {            vector<int> result(size(a));            for (int i = 0; i < k; ++i) {                if (!a[i]) {                    continue;                }                for (int j = 0; j < k; ++j) {                    if (!b[j]) {                        continue;                    }                    result[(i + j) % k] = ((result[(i + j) % k] + static_cast<int64_t>(a[i]) * b[j]) % MOD);                }            }            return result;        };         vector<vector<int>> adj(size(nums));        for (int v = 1; v < size(parent); ++v) {            adj[parent[v]].emplace_back(v);        }        vector<vector<vector<int>>> dp(size(nums), vector<vector<int>>(2, vector<int>(k)));        for (int u = size(nums) - 1; u >= 0; --u) {            vector<vector<int>> new_dp(2, vector<int>(k));            new_dp[0][0] = 1;            new_dp[1][nums[u] % k] = 1;            for (const auto& v : adj[u]) {                vector<int> dp2(k);                for (int i = 0; i < k; ++i) {                    dp2[i] = (dp[v][0][i] + dp[v][1][i]) % MOD;                }                new_dp[0] = merge(new_dp[0], dp2);                new_dp[1] = merge(new_dp[1], dp[v][0]);            }            dp[u] = move(new_dp);        }        return ((dp[0][0][0] + dp[0][1][0] - 1LL) + MOD) % MOD;    }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗