当前位置:网站首页>全排列的代码 (递归写法)

全排列的代码 (递归写法)

2022-07-05 05:31:00 Java全栈研发大联盟

代码如下:

public static List<String> getSubstring(String[] words) {
    
        if(words.length==1){
    
            return Arrays.asList(words);
        }
        List<String> resultList = new ArrayList<>();
        for (int i = 0; i < words.length; i++) {
    
            String[] strings = Arrays.copyOf(words, words.length);
            strings = changeArray(strings, i);
            List<String> stringList = getSubstring(strings);
            for (String str : stringList) {
    
                resultList.add(words[i] + str);
            }
        }
        return resultList;
    }

    public static String[] changeArray(String[] words, int i) {
    
        for (int k = i; k < words.length - 1; k++) {
    
            words[k] = words[k + 1];
        }
        return Arrays.copyOf(words, words.length - 1);
    }

如果测试

String[] words = {
    "1", "2", "3"};
List<String> substring = getSubstring(words);
System.out.println(substring);

打印结果:
在这里插入图片描述

原网站

版权声明
本文为[Java全栈研发大联盟]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_40241957/article/details/125603333