To write an anagram solution of the type you are binding, the algorithm you request is not required. It is also VERY expensive.
Let's look at a 6-letter word, for example, MONKEY . All 6 letters of the word are different, so you should create:
- 6 * 5 * 4 * 3 * 2 * 1 different 6-letter words
- 6 * 5 * 4 * 3 * 2 different 5-letter words
- 6 * 5 * 4 * 3 different 4-letter words
- 6 * 5 * 4 different three-letter words
- 6 * 5 different two-word words
- A total of 1950 words
Now, apparently, you are not trying to spit out all the words of 1950 (for example, "OEYKMN") in the form of anagrams (as they are, but most of them are also gibberish). I assume that you have a dictionary of legal English words, and you just want to check if any of these words are anagrams of the query word, with the possibility not to use all the letters.
If so, then the problem is simple.
To determine if 2 words are anagrams of each other, all you have to do is calculate how many times each letter is used and compare these numbers!
We restrict ourselves to only 26 letters, case insensitive. You need to write a countLetters function that takes a word and returns an array of 26 numbers. The first number in the array corresponds to the count of the letter A in the word, the second number corresponds to the count of B , etc.
Then the two words W1 and W2 are exact anagrams if countLetters(W1)[i] == countLetters(W2)[i] for every i ! That is, every word uses every letter exactly the same number of times!
For what I would call subanabrams ( MONEY is a subanagram of MONKEY ), W1 is a subanagram of W2 if countLetters(W1)[i] <= countLetters(W2)[i] for every i ! That is, a subanagram can use less than certain letters, but no more!
(note: MONKEY also a subanagram of MONKEY ).
This should give you a reasonably fast algorithm in which the query string is set, all you have to do is read the dictionary once, comparing the array of letter counters of each word with the array of letter counters of the query word. You can do a little optimization, but that should be good enough.
Alternatively, if you want to get maximum performance, you can pre-process the dictionary (which is known in advance) and create an oriented acyclic graph of the relationship between the anagrams.
Here is part of such a graph to illustrate:
D=1,G=1,O=1 ----------> D=1,O=1 {dog,god} \ {do,od} \ \-------> G=1,O=1 {go}
Basically, each node is a bucket for all words that have the same array of letter counts (i.e. they are exact anagrams). Then there is a node from N1 to N2 if the array N2 is <= (as defined above) N1 array (you can perform a transient reduction to store the least number of edges).
Then, to list all the meanings of the word, you need to find the node corresponding to its letter counting array and recursively examine all the nodes available from this node. All of their buckets contain subanagrams.