Skip to content

Commit

Permalink
Solve LeetCode #90 'Subsets II' [Medium].
Browse files Browse the repository at this point in the history
  • Loading branch information
eminencegrs committed Dec 11, 2024
1 parent e9fa6bc commit 2c81f6d
Show file tree
Hide file tree
Showing 2 changed files with 133 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
namespace LeetCode.Challenges.Problems00xx.N_0090_SubsetsII;

public static class Solution
{
public static IList<IList<int>> Subsets(int[] numbers)
{
var result = new List<IList<int>>();
Dfs(0, []);
return result;

void Dfs(int index, IList<int> subset)
{
if (index == numbers.Length)
{
result.Add(new List<int>(subset));
return;
}

subset.Add(numbers[index]);
Dfs(index + 1, subset);

subset.RemoveAt(subset.Count - 1);

while (index + 1 < numbers.Length && numbers[index] == numbers[index + 1])
{
index++;
}

Dfs(index + 1, subset);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
using FluentAssertions;
using LeetCode.Challenges.Problems00xx.N_0090_SubsetsII;
using Xunit;

namespace LeetCode.Challenges.UnitTests.Problems00xx.N_0090_SubsetsII;

public class SolutionTests
{
[Theory]
[MemberData(nameof(TestData))]
public void GivenNumbers_WhenSubsets_ThenResultAsExpected(int[] numbers, IList<IList<int>> expectedResult)
{
Solution.Subsets(numbers).Should().BeEquivalentTo(expectedResult);
}

public static IEnumerable<object[]> TestData()
{
yield return
[
new[] { 0 },
new List<IList<int>>
{
new List<int> { 0 },
new List<int>()
}
];

yield return
[
new[] { 1, 1 },
new List<IList<int>>
{
new List<int> { 1, 1 },
new List<int> { 1 },
new List<int>()
}
];

yield return
[
new[] { 1, 2 },
new List<IList<int>>
{
new List<int> { 1, 2 },
new List<int> { 1 },
new List<int> { 2 },
new List<int>()
}
];

yield return
[
new[] { 1, 2, 2 },
new List<IList<int>>
{
new List<int> { 1, 2, 2 },
new List<int> { 1, 2 },
new List<int> { 1 },
new List<int> { 2, 2 },
new List<int> { 2 },
new List<int>()
}
];

yield return
[
new[] { 1, 2, 3 },
new List<IList<int>>
{
new List<int> { 1, 2, 3 },
new List<int> { 1, 2 },
new List<int> { 1, 3 },
new List<int> { 1 },
new List<int> { 2, 3 },
new List<int> { 2 },
new List<int> { 3 },
new List<int>()
}
];

yield return
[
new[] { 1, 2, 2, 3 },
new List<IList<int>>
{
new List<int> { 1, 2, 2, 3 },
new List<int> { 1, 2, 2 },
new List<int> { 1, 2, 3 },
new List<int> { 1, 2 },
new List<int> { 1, 3 },
new List<int> { 1 },
new List<int> { 2, 2, 3 },
new List<int> { 2, 2 },
new List<int> { 2, 3 },
new List<int> { 2 },
new List<int> { 3 },
new List<int>()
}
];
}
}

0 comments on commit 2c81f6d

Please sign in to comment.