LichongQ / record

for record something necessary
0 stars 0 forks source link

数据结构和算法 #5

Open LichongQ opened 6 years ago

LichongQ commented 6 years ago
LichongQ commented 6 years ago

获取数组中元素的全排列

listAll(array, "");
 public static void listAll(ArrayList<String> array, String prefix)
{
    if ( prefix != null && !prefix.isEmpty() )
            System.out.println(prefix);

    for (int ii=0; ii<array.size(); ii++)
    {
        ArrayList<String> temp = new ArrayList<>(array);
        listAll(temp, prefix + temp.remove(ii));
    }
}

非全排列

    public static void listAll_v2(String s, String prefix)
    {
        int[] index = new int[s.length()];
        for (int ii=0; ii<s.length(); ii++)
        {
            index[ii] = s.indexOf(s.charAt(ii));
        }

        if (prefix != null && !prefix.isEmpty() &&  prefix.length() == 3)
        {
            System.out.println(prefix);
        }

        for (int jj=0; jj<s.length(); jj++)
        {
            if (index[jj] == jj)
            {
                listAll_v2(s.substring(1), prefix + s.substring(0, 1));
            }
            s = s.substring(1) + s.substring(0,1);
        }
    }