1. Permutation Validation
Intuition
Generate every permutation of people and check if every person's height and k constraints are satisfied.
Algorithm
- Step 1: Generate all permutations of the array people.
- Step 2: For each permutation, verify if for every person i, exactly k_i people with height >= h_i precede them.
- Step 3: If valid, return that permutation.
- Step 4: Continue until valid queue is found.
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution { bool isValid(const vector<vector<int>>& p) { int n = p.size(); for (int i = 0; i < n; ++i) { int count = 0; for (int j = 0; j < i; ++j) { if (p[j][0] >= p[i][0]) count++; } if (count != p[i][1]) return false; } return true; }public: vector<vector<int>> reconstructQueue(vector<vector<int>>& people) { sort(people.begin(), people.end()); do { if (isValid(people)) return people; } while (next_permutation(people.begin(), people.end())); return {}; }}; int main() { Solution sol; vector<vector<int>> people = {{7, 0}, {4, 4}, {7, 1}, {5, 0}, {6, 1}, {5, 2}}; auto res = sol.reconstructQueue(people); cout << "Reconstructed Queue:" << endl; for (const auto& p : res) cout << "[" << p[0] << "," << p[1] << "] "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N! * N) - Space complexity:
O(N)