-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutations.cs
More file actions
50 lines (43 loc) · 1.68 KB
/
Permutations.cs
File metadata and controls
50 lines (43 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Algorithms.Problem.InterviewCake
{
[TestClass]
public class Permutations
{
public ISet<string> GetPermutations(string inputString)
{
// Base case
if (inputString.Length <= 1)
{
return new HashSet<string>(inputString.Select(c => new string(c, 1)));
}
string allCharsExceptLast = inputString.Substring(0, inputString.Length - 1);
char lastChar = inputString[inputString.Length - 1];
// Recursive call: get all possible permutations for all chars except last
ISet<string> permutationsOfAllCharsExceptLast = this.GetPermutations(allCharsExceptLast);
// Put the last char in all possible positions for each of the above permutations
var permutations = new HashSet<string>();
foreach (string permutationOfAllCharsExceptLast in permutationsOfAllCharsExceptLast)
{
for (int position = 0; position <= allCharsExceptLast.Length; position++)
{
string permutation = permutationOfAllCharsExceptLast.Substring(0, position)
+ lastChar
+ permutationOfAllCharsExceptLast.Substring(position);
permutations.Add(permutation);
}
}
return permutations;
}
[TestMethod]
public void TestPermutations()
{
var permutations = this.GetPermutations("cats");
}
}
}