Skip to content

递归字符串排列 #1

@maskleo

Description

@maskleo

https://www.2cto.com/kf/201703/614471.html

public static void main(String[] args) {
        //permute("ABCD");
        String str = "ABC";
        insert(new ArrayList<>(str.length()), str.toCharArray());
    }

    public static void insert(List<Character> result, char[] remain) {
        if(result.size() == remain.length) {
            System.out.println(result);
            return;
        }
        char temp = remain[result.size()];
        for (int i = 0; i <= result.size(); i++) {
            result.add(i, temp);
            insert(result, remain);
            result.remove(i);
        }
    }

原理:

  • 每次从原来的数组中取一个
  • 每次取的新的字符在原来的字符逐个位置插入,例如 AB, 拿到C之后 逐个位置插入得到CAB,ACB
    ABC
//字符全排列打印驱动方法
    public static void permute02(String str) {
        char[] strArray = str.toCharArray();
        permute(strArray, 0, strArray.length - 1);
    }

    /**
     * 采用递归,打印n个字符全排列
     * 方法目的是为了得到在low与high之间字符的全排列
     * 将字符数组中第一个字符依次与其他字符交换位置
     * 然后将low推进一位,得到n-1个字符的全排列,以此得到所有字符全排列
     *
     * @param list 字符数组
     * @param low  最低位
     * @param high 最高位
     */
    private static void permute(char[] list, int low, int high) {
        int i;
        if(low == high) {
            StringBuffer cout = new StringBuffer();
            for (i = 0; i <= high; i++)
                cout.append(list[i]);
            System.out.println(cout);
        } else {
            for (i = low; i <= high; i++) {
                if(i != low){
                    System.out.println("low:" + low + ",i:" + i);
                }
                //1.交换低位位置
                char temp = list[low];
                list[low] = list[i];
                list[i] = temp;
                //2.进入下一级
                permute(list, low + 1, high);
                //3.复原位置
                temp = list[low];
                list[low] = list[i];
                list[i] = temp;
            }
        }
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions