How to generate all unique combinations of a list of words?
I have a list of words like:
List={"word1", "word2", "word3", ....}
How can i generate a "two word length" list of all unique combination of these words?
For example, if above list contains only three words then the output might be like:
word1 word2
word1 word3
word2开发者_如何学编程 word1
word2 word4
word3 word1
word3 word2
Also, note that "word1 word2"
is not
same as "word2 word1"
.
I know a simplest solution like this:
for i=1 to N
for j=1 to N
if(i!=j) then
print List[i]+" "+List[j]
But this has O(n2) complexity. So, what is the best algorithm with least worst case complexity for achieving the same.
The output of the algorithm contains O(n^2)
elements. Since every output element needs to be attended to, you can't hope to achieve better than O(n^2)
time complexity.
精彩评论