leetcode 5087 letter tile possibility


标签:数论,dfs

题目

You have a set of tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make.

Example 1:

Input: "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".

Example 2:

Input: "AAABBC"
Output: 188

Note:

  1. 1 <= tiles.length <= 7
  2. tiles consists of uppercase English letters.

思路

  1. 如果给定字符串长度, 比如“A“A”A“B”B”可以组成的字符串个数,容易想到用排列组合的公式
  2. 此题不给定长度,可以用dfs求出所有情况
  3. 因为dfs过程可能出现重复状态,用set记录所有可能的状态,为了让相同状态的好比较,开始时对字符串进行排序操作。这样相同的字串(字符全部相同)的序列必然一致

code dfs+排列组合

class Solution {
public:
    int fact[8] = {1, 1, 2, 6, 24, 120, 720, 5040  };
    set<string> st;
    int dfs(string& tiles, string seq, int postfix){
      //  cout << seq << "--"<<endl;
        if (postfix>=tiles.length()){
            if(st.find(seq) != st.end()) return 0;
            vector<int> cnt(26, 0);
            for(auto ch : seq) {
            //    cout<<ch<<endl;
                cnt[ch-'A'] ++;
            }
            int ans = fact[seq.length()];
            for(auto ct : cnt) {
                ans /= fact[ct];}
            st.insert(seq);
            return ans;
        }

        return dfs(tiles, seq, postfix+1) + dfs(tiles, seq + tiles[postfix], postfix+1);
    }
    int numTilePossibilities(string tiles) {
        sort(begin(tiles), end(tiles));
        string string1="";
        string1 += tiles[0];
        //cout<<"--"<<string1<<endl;
        return dfs(tiles, "", 1) + dfs(tiles,string1, 1) - 1;
    }
};

小结

c++的char和string

  1. char to string的错误写法

    string str = "" + 'c'; //error
    string str = 'c'; //error
    
  2. char to string 的正确写法

    string str = "";
    str += 'c';
    str.push_back('c');
    

C++的map和set判断是否存在某个值

  1. map

    map<int, int> mp;
    if (mp.count(key) > 0) cout << "key exits" << endl;
    
  2. set

    set<int> st;
    if(st.find(key) != end(st)) cout << " key in set " <<endl;
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值