| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.Permutations; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class PermutationsBacktracking : IPermutations |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n * n!) |
| | 19 | | /// Space complexity - O(n * n!) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="nums"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public IList<IList<int>> Permute(int[] nums) |
| 3 | 24 | | { |
| 3 | 25 | | var result = new List<IList<int>>(); |
| | 26 | |
|
| 3 | 27 | | Backtrack(nums, 0, nums.Length, result); |
| | 28 | |
|
| 3 | 29 | | return result; |
| 3 | 30 | | } |
| | 31 | |
|
| | 32 | | private static void Backtrack(IList<int> nums, int start, int end, ICollection<IList<int>> result) |
| 23 | 33 | | { |
| 23 | 34 | | if (start == end) |
| 9 | 35 | | { |
| 9 | 36 | | result.Add(new List<int>(nums)); |
| 9 | 37 | | } |
| | 38 | | else |
| 14 | 39 | | { |
| 68 | 40 | | for (var i = start; i < end; i++) |
| 20 | 41 | | { |
| 20 | 42 | | (nums[i], nums[start]) = (nums[start], nums[i]); |
| | 43 | |
|
| 20 | 44 | | Backtrack(nums, start + 1, end, result); |
| | 45 | |
|
| 20 | 46 | | (nums[i], nums[start]) = (nums[start], nums[i]); |
| 20 | 47 | | } |
| 14 | 48 | | } |
| 23 | 49 | | } |
| | 50 | | } |