你有一套活字字模 tiles,其中每个字模上都刻有一个字母 tiles[i]。返回你可以印出的非空字母序列的数目。
示例 1:
输入:"AAB"
输出:8
解释:可能的序列为 "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA"。
示例 2:
输入:"AAABBC"
输出:188
提示:
1 <= tiles.length <= 7
tiles 由大写英文字母组成
public class Solution {
public int NumTilePossibilities(string tiles)
{
var set = new HashSet<string>();
var list = tiles.ToList();
// brute force all lengths
// length options: 1, 2, 3, 4, 5, 6, 7
for (int i = 1; i <= tiles.Length; i++)
{
NumTilePossibilitiesHelper(new StringBuilder(), set, list, i);
}
return set.Count;
}
private static void NumTilePossibilitiesHelper(
StringBuilder sequence,
HashSet<string> set,
List<char> tiles,
int length)
{
// base case
if (sequence.Length == length)
{
set.Add(sequence.ToString());
return;
}
// please consider the next char for all possible chars
int backtrackingLength = sequence.Length;
for (int i = 0; i < tiles.Count; i++)
{
var current = tiles[i];
sequence.Append(current);
// remove current char from the list
tiles.RemoveAt(i);
NumTilePossibilitiesHelper(sequence, set, tiles, length);
// insert current char to the list
// List.Insert()
tiles.Insert(i, current);
// StringBuilder.Remove(start, length)
sequence.Remove(backtrackingLength, sequence.Length - backtrackingLength);
}
}
}