LeetCode 1079. Letter Tile Possibilities

原题链接在这里:https://leetcode.com/problems/letter-tile-possibilities/

题目:

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.

题解:

Accumlate all the possibilities during the process of calculating permutations.

Time Complexity: expontential.

Space: O(expontential).

AC Java:

 1 class Solution {
 2     public int numTilePossibilities(String tiles) {
 3         if(tiles == null || tiles.length() == 0){
 4             return 0;
 5         }
 6         
 7         HashSet<String> hs = new HashSet<>();
 8         char [] arr = tiles.toCharArray();
 9         boolean [] used = new boolean[tiles.length()];
10         dfs(arr, used, "", hs);
11         return hs.size();
12     }
13     
14     private void dfs(char [] arr, boolean [] used, String item, HashSet<String> hs){        
15         for(int i = 0; i<used.length; i++){
16             if(!used[i]){
17                 used[i] = true;
18                 hs.add(item+arr[i]);
19                 dfs(arr, used, item+arr[i], hs);
20                 used[i] = false;
21             }
22         }
23     }
24 }

Count the frequency for letter in tiles.

AAB -> A:2, B:1.

Take one A sum++. 

The rest is A:1, B:1. All the combinations of rest should be accumlated back to sum. sum += dfs(rest). A, AB, B, BA.

Time Complexity: O(expontential).

Space: O(n). n = tiles.length. n level stack space

AC Java:

 1 class Solution {
 2     public int numTilePossibilities(String tiles) {
 3         if(tiles == null || tiles.length() == 0){
 4             return 0;
 5         }
 6         
 7         int [] count = new int[26];
 8         for(int i = 0; i<tiles.length(); i++){
 9             count[tiles.charAt(i)-'A']++;
10         }
11         
12         return dfs(count);
13     }
14     
15     private int dfs(int [] count){
16         int sum = 0;
17         for(int i = 0; i<count.length; i++){
18             if(count[i] == 0){
19                 continue;
20             }
21             
22             sum++;
23             count[i]--;
24             sum += dfs(count);
25             count[i]++;
26         }
27         
28         return sum;
29     }
30 }
原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11791078.html