leetcode1079. 活字印刷(回溯)

你有一套活字字模 tiles,其中每个字模上都刻有一个字母 tiles[i]。返回你可以印出的非空字母序列的数目。

注意:本题中,每个活字字模只能使用一次。

示例 1:

输入:“AAB”
输出:8
解释:可能的序列为 “A”, “B”, “AA”, “AB”, “BA”, “AAB”, “ABA”, “BAA”。

代码

class Solution {
    int n,ans=0;
    public int numTilePossibilities(String tiles) {

        n=tiles.length();
        Map<Character,Integer> map=new HashMap<>();
        for(char c:tiles.toCharArray()) map.put(c,map.getOrDefault(c,0)+1);//统计可用字母
         numTile(map,0);
         return ans-1;
    }
    public void numTile(Map<Character,Integer> map,int level) {

        ans++;
        if(level==n) return;
        for (char c:map.keySet())//可选择的字母
        {
            if(map.get(c)<1) continue;//没有剩下的了
            map.put(c,map.get(c)-1);
            numTile(map, level+1);
            map.put(c,map.get(c)+1);//回溯
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44560620/article/details/107728385