classSolution { public: boolcheckOnesSegment(string s){ int state = 0; // 0: not see 1 // 1: see 1 and now 1 // 2: see 1 but now 0 for (char c : s) { if (c == '0') { if (state == 0) { state = 0; } elseif (state == 1) { state = 2; } else { state = 2; } } else { // c == '1' if (state == 0) { state = 1; } elseif (state == 1) { state = 1; } else { returnfalse; } } } returntrue; } };
Time complexity: O(N), space complexity: O(1).
1785. Minimum Elements to Add to Form a Given Sum
Greedy. Add or subtract limit/-limit each time, using the largest step size to get the minimum number of steps. Note: the constraints intentionally set a trap here. Using int to sum nums will overflow. Of course, Python does not have this issue.
1786. Number of Restricted Paths From First to Last Node
The problem statement is hard to understand, but the problem itself is not difficult. Use Dijkstra to compute distanceToLastNode(x), then a memoized dfs is enough.
To be honest, I thought about this problem for a long time and had no idea. I even searched Google for quite a while and felt it might be an original known problem. But I did not find it. After the contest, someone in the group posted a link, and it really was an original problem: original problem link. It seems searching for problems is also a skill. Some people can find it and copy the code, and that also counts as their ability.
First, we can observe that in the final state, every k numbers repeat. Therefore, we can determine that we only need to compute the first k numbers so their XOR is 0. Of course, when calculating cost, we still need to consider the later numbers.
Then, based on the constraints, guess that this is a DP with time complexity O(1024*n). Then construct the state transition equation.
classSolution { constint MAX_NUMS = 1 << 10; public: intminChanges(vector<int>& nums, int k){ constint n = nums.size(); // the total size of Set[i] vector<int> totalCost(k); // cnt[i][j]: the count of j in Set[i] vector<unordered_map<int, int>> cnt(k); for (int i = 0; i < n; ++i) { ++totalCost[i % k]; ++cnt[i%k][nums[i]]; } // the cost to set Set[i] to v auto cost = [&](constint i, constint v) -> int { return totalCost[i] - cnt[i][v]; }; // dp[i][d]: the minimum cost to make first i XOR equal to d vector<vector<int>> dp(k, vector<int> (MAX_NUMS, numeric_limits<int>::max())); int minLastDp = numeric_limits<int>::max(); for (int d = 0; d < MAX_NUMS; ++d) { dp[0][d] = totalCost[0] - cnt[0][d]; minLastDp = min(minLastDp, dp[0][d]); } for (int i = 1; i < k; ++i) { int minDp = numeric_limits<int>::max(); for (int d = 0; d < MAX_NUMS; ++d) { dp[i][d] = minLastDp + totalCost[i]; for (int j = i; j < n; j += k) { dp[i][d] = min(dp[i][d], dp[i-1][d^nums[j]] + cost(i, nums[j])); } minDp = min(minDp, dp[i][d]); } minLastDp = minDp; } return dp[k-1][0]; } };
Time complexity: O(k * 1024 * n / k) = O(1024 * n), space complexity: O(k * 1024).