【Java.算法】使用Java输出四个名字的全排列

【代码】

package test230421;

import java.util.ArrayList;
import java.util.List;

public class Arrange {
    static List<List<Integer>> result = new ArrayList<>();
    
    public static void main(String[] args) {
        final String[] names= {"张三","李四","王五","赵六"};
        int[] arr = {0,1,2,3};
  
        Arrange h1 = new Arrange();
        h1.dfs(arr,new ArrayList<>());
        
        int idx=0;
        for (List<Integer> re : result) {
            List<String> joinedNames=new ArrayList<String>(names.length);
            for(int i=0;i<names.length;i++) {
                joinedNames.add(names[re.get(i)]);
            }
            
            System.out.println(String.format("%02d",++idx)+"."+String.join(",", joinedNames));
        }  
    }
  
    public List<List<Integer>> dfs( int[] arr,List<Integer> list){
        List<Integer> temp = new ArrayList<>(list);
        if (arr.length == list.size()){
            result.add(temp);
        }
        for (int i=0;i<arr.length;i++){
            if (temp.contains(arr[i])){
                continue;
            }
            temp.add(arr[i]);
            dfs(arr,temp);
            temp.remove(temp.size()-1);
        }
        return result;
    }
}

【输出】

01.张三,李四,王五,赵六
02.张三,李四,赵六,王五
03.张三,王五,李四,赵六
04.张三,王五,赵六,李四
05.张三,赵六,李四,王五
06.张三,赵六,王五,李四
07.李四,张三,王五,赵六
08.李四,张三,赵六,王五
09.李四,王五,张三,赵六
10.李四,王五,赵六,张三
11.李四,赵六,张三,王五
12.李四,赵六,王五,张三
13.王五,张三,李四,赵六
14.王五,张三,赵六,李四
15.王五,李四,张三,赵六
16.王五,李四,赵六,张三
17.王五,赵六,张三,李四
18.王五,赵六,李四,张三
19.赵六,张三,李四,王五
20.赵六,张三,王五,李四
21.赵六,李四,张三,王五
22.赵六,李四,王五,张三
23.赵六,王五,张三,李四
24.赵六,王五,李四,张三

【参考资料】

https://www.jb51.net/article/252294.htm

posted @ 2023-01-09 23:16  逆火狂飙  阅读(154)  评论(0)    收藏  举报
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东