Time: O(n^n), Space: O(n)