​LeetCode解法汇总1079. 活字印刷

 目录链接:

力扣编程题-解法汇总_分享+记录-CSDN博客

GitHub同步刷题项目:

https://github.com/September26/java-algorithms

原题链接:力扣


描述:

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

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

示例 1:

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

示例 2:

输入:"AAABBC"
输出:188

示例 3:

输入:"V"
输出:1

提示:

  • 1 <= tiles.length <= 7
  • tiles 由大写英文字母组成

解题思路:

* 解题思路:
* 用一种最笨的办法,就是穷举所有可能。设置数组uses记录状态,如果用过了就设置为true,继续递归。递归完成设置回false。
 

代码:

public class Solution1079 {

    public int numTilePossibilities(String tiles) {
        if (tiles.length() == 1) {
            return 1;
        }
        Set<String> set = new HashSet<>();
        char[] chars = tiles.toCharArray();
        boolean[] uses = new boolean[chars.length];
        for (int i = 1; i < chars.length; i++) {
            search(set, chars, uses, "");
        }
        return set.size() - 1;
    }

    private void search(Set<String> set, char[] chars, boolean[] uses, String str) {
        set.add(str);
        for (int i = 0; i < uses.length; i++) {
            if (uses[i]) {
                continue;
            }
            uses[i] = true;
            search(set, chars, uses, str + chars[i]);
            uses[i] = false;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

失落夏天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值