Permutation of a String Without Duplicate
All permutation of a string that has only unique characters.
Solution:
- It base on previous permutation for example:
- P(a1) = a1
- P(a1,a2) = P(a1) + a2 = a2a1 + a1a2
- P(a1,a2,a3) = P(a1,a2) + a3 = (a2a1 + a1a2) + a3 = (a3a2a1 + a2a3a1 + a2a1a3 ) + (a3a1a2 + a1a3a2 + a1a2a3)
Algorithm:
- Base Case : if string is null then return null
- Create lists permutationList of all permutations
- If string is length = 0 then
- add permutationList.add (“”)
- Else
- Get first character of string
- Recursively call with remaining string
- Iterate all words returned by previous call
- Add first character to all position of word from start to end
- Add altered word to permutationList
- Return permutationList
Latest Source Code:
Github: PermutationOfStringWithoutDuplicate.java
Output:
Permutation(a): [a] Permutation(ab): [ab, ba] Permutation(abc): [abc, bac, bca, acb, cab, cba]