1079. Letter Tile Possibilities

问题:给定一串由A~Z构成的字符串(允许重复)。

从中选取任意个字符,构成新的字符串,求可构成的字符串个数。

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

Example 2:
Input: tiles = "AAABBC"
Output: 188

Example 3:
Input: tiles = "V"
Output: 1

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

  

解法:DFS(深度优先搜索),Backtracking(回溯算法)

  • 状态:到目前位置为止,构成的前部字符串:
    • 特别的⚠️ ,当选择本字符时,同时就产生了一个解,res++。(由于要求的可构成字符串长度不限。)
    • 再进行递归去寻找下一个字符位置,求的解累加。
  • 选择:除去已经使用过的字符后,余下count[i]!=0的所有字符。
  • 退出递归:count所有字符都为空,即字符用完。

⚠️  注意:

本问题的难点在于:重复字符在相同位置上,只相当于构成同一个字符串。

-> 解决:使用字符计数数组,count[26],记录每个字符出现了多少个。

对于下一个字符的选择,只能在不同的字符中做选择。

如,AAB,只能选择A和B,两种选择。

参考说明:LeetCode Thought:

input: AAB
count: A -> 2, B -> 1

For sequence of length 1:

We can pick either A, or B.
So we have "A", "B".
For sequence of length 2:

We build it based on "sequence of length 1"
For "A":
count: A -> 1, B -> 1
We can still pick either A, or B
So we have "AA", "AB"
For "B":
count: A -> 2, B -> 0
We can only pick A
So we have "BA"
For sequence of length 3: blablabla

代码参考:

 1 class Solution {
 2 public:
 3     void dfs(int& res, int count[]) {
 4         for(int i=0; i<26; i++) {
 5             if(count[i]==0) continue;
 6             res++;
 7             count[i]--;
 8             dfs(res, count);
 9             count[i]++;
10         }
11         return;
12     }
13     int numTilePossibilities(string tiles) {
14         int res=0;
15         int count[26]={0};
16         for(char a:tiles) {
17             count[a-'A']++;
18         }
19         dfs(res, count);
20         return res;
21     }
22 };

  

原文地址:https://www.cnblogs.com/habibah-chang/p/14348765.html