interview-preparation / what-we-do

0 stars 8 forks source link

[Recursion and Dynamic Programming] interview questions #8 #101

Closed rygh4775 closed 5 years ago

rygh4775 commented 5 years ago

Permutations with Duplicates: Write a method to compute all permutations of a string whose characters are not necessarily unique. The list of permutations should not have duplicates.

rygh4775 commented 5 years ago

Approach

P(a- >1 I b- >4 I C->1) = {a + P(a->6 I b- >4 I c->1)} + {b + P(a->1 I b->3 I c->1)} + {c + P(a->1 I b->4 I c- >0) } P(a- >2 I b->3 I c->1) = {a + P(a->1 I b- >3 I c->1)} + {b + P(a- >2 I b->2 I c->1)} + {c + P(a->2 I b->3 I c->6)} P(a->2 I b->4 I c ->0) = {a + P(a->1 I b- >4 I c->6)} + {b + P(a->2 I b->3 I c->6)}

### Solution
```java
ArrayList<String> printPerms(String s) {
    ArrayList<String> result = new ArrayList<>();
    HashMap<Character, Integer> map = buildFreqTable(s);
    printPerms(map, "", s.length(), result);
    return result;
}

private HashMap<Character, Integer> buildFreqTable(String s) {
    HashMap<Character, Integer> map = new HashMap<>();
    for(Character c : s.toCharArray()) {
        if(!map.containsKey(c)) {
            map.put(c, 0);
        }
        map.put(c, map.get(c) + 1);
    }
    return map;
}

private void printPerms(HashMap<Character, Integer> map, String prefix, int remaining, ArrayList<String> result) {
    if(remaining == 0) {
        result.add(prefix);
        return;
    }

    for (Character c : map.keySet()) {
        int count = map.get(c);
        if(count > 0) {
            map.put(c, count -1);
            printPerms(map, prefix + c, remaining -1, result);
            map.put(c, count);
        }
    }
}

Time complexity

rygh4775 commented 5 years ago

input이 abc일 경우 prefix trace


a
ab
abc
ac
acb
b
ba
bac
bc
bca
c
ca
cab
cb
cba