试图解决“字母拼写可能性”问题
对于给定的输入,要求计算可能的序列数。不知道我的程序出了什么问题。
该程序适用于以下输入
输入:“ AAB”
输出:8
说明:可能的顺序为“ A”,“ B”,“ AA”,“ AB”,“ BA”,“ AAB”,“ ABA”,“ BAA”。
当我将输入更改为此时程序失败
输入:“ AAABBC”
预期输出:188(正确答案)。
但是程序返回-164
代码
int[] factorial = new int[]{1,1,2,6,24,120,720};
HashMap<String, Integer> map = new HashMap<String,Integer>();
public int numTilePossibilities(String tiles) {
char[] array = tiles.toCharArray();
int total_sequences = 0;
int total = array.length;
for(int i=0; i<array.length; i++)
{
addToMap(array[i]);
}
for(int digit = 1; digit<=total; digit++)
{
int numerator = factorial[total];
int denominator = (factorial[total-digit] * getRepetitions());
total_sequences += Math.round((float)((float)numerator/(float)denominator));
System.out.println("Digit "+digit+" Sequences "+Math.round((float)((float)numerator/(float)denominator))+" N "+ numerator+" D"+denominator+" Rep"+ getRepetitions() );
}
return total_sequences;
}
private Integer getRepetitions()
{
int denominator = 1;
for(String key : map.keySet())
{
if(map.get(key)==1)
{
continue;
}
denominator= ((denominator)*factorial[map.get(key)]);
}
return denominator;
}
private void addToMap(char tile)
{
Integer counter = map.get(tile+"");
if(counter == null)
{
counter = 0;
}
counter++;
map.put(tile+"",counter);
}
}