| | 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.CombinationSum2; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class CombinationSum2Backtracking : ICombinationSum2 |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(2^n * k) |
| | 19 | | /// Space complexity - O(2^n * k) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="candidates"></param> |
| | 22 | | /// <param name="target"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public IList<IList<int>> CombinationSum2(int[] candidates, int target) |
| 2 | 25 | | { |
| 2 | 26 | | Array.Sort(candidates); |
| | 27 | |
|
| 2 | 28 | | var result = new List<IList<int>>(); |
| | 29 | |
|
| 2 | 30 | | Backtrack(result, new List<int>(), candidates, target, 0); |
| | 31 | |
|
| 2 | 32 | | return result; |
| 2 | 33 | | } |
| | 34 | |
|
| | 35 | | private static void Backtrack(ICollection<IList<int>> result, IList<int> tempList, IReadOnlyList<int> candidates, |
| | 36 | | int remain, int start) |
| 24 | 37 | | { |
| 24 | 38 | | switch (remain) |
| | 39 | | { |
| | 40 | | case 0: |
| 6 | 41 | | result.Add(new List<int>(tempList)); |
| | 42 | |
|
| 6 | 43 | | break; |
| | 44 | | case > 0: |
| 18 | 45 | | { |
| 94 | 46 | | for (var i = start; i < candidates.Count; i++) |
| 46 | 47 | | { |
| 46 | 48 | | if (i > start && candidates[i] == candidates[i - 1]) |
| 7 | 49 | | { |
| 7 | 50 | | continue; |
| | 51 | | } |
| | 52 | |
|
| 39 | 53 | | if (candidates[i] > remain) |
| 17 | 54 | | { |
| 17 | 55 | | break; |
| | 56 | | } |
| | 57 | |
|
| 22 | 58 | | tempList.Add(candidates[i]); |
| | 59 | |
|
| 22 | 60 | | Backtrack(result, tempList, candidates, remain - candidates[i], i + 1); |
| | 61 | |
|
| 22 | 62 | | tempList.RemoveAt(tempList.Count - 1); |
| 22 | 63 | | } |
| | 64 | |
|
| 18 | 65 | | break; |
| | 66 | | } |
| | 67 | | } |
| 24 | 68 | | } |
| | 69 | | } |