Generating all permutations of a certain length

后端 未结 3 675
-上瘾入骨i
-上瘾入骨i 2020-12-06 12:59

Suppose we have an alphabet \"abcdefghiklimnop\". How can I recursively generate permutations with repetition of this alphabet in groups of FIVE in an efficient way?

3条回答
  •  时光说笑
    2020-12-06 13:10

    This is can be easily done using bit manipulation.

    private void getPermutation(String str, int length)
            {
                if(str==null)
                    return;
                Set StrList = new HashSet();
                StringBuilder strB= new StringBuilder();
                for(int i = 0;i < (1 << str.length()); ++i)
                {
                    strB.setLength(0); //clear the StringBuilder
                    if(getNumberOfOnes(i)==length){
                      for(int j = 0;j < str.length() ;++j){
                        if((i & (1 << j))>0){  // to check whether jth bit is set (is 1 or not)
                            strB.append(str.charAt(j));
                        }
                    }
                    StrList.add(strB.toString());
                    }
                }
                System.out.println(Arrays.toString(StrList.toArray()));
            }
    
        private int getNumberOfOnes (int n) // to count how many numbers of 1 in binary representation of n
        {
            int count=0;
            while( n>0 )
            {
            n = n&(n-1);
               count++;
            }
            return count;
        }
    

提交回复
热议问题