【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.赵六,王五,李四,张三
【参考资料】
分类:
Java.Algorithm
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
2020-01-09 按月查询数据
2020-01-09 Oracle SQL 判断某表是否存在
2020-01-09 在Python程序中执行linux命令
2020-01-09 在Oracle中十分钟内创建一张千万级别的表
2018-01-09 求边长为一的正方体中,面对角线组成的正四面体体积.
2017-01-09 关于后台数据库正常存储中文通过Ajax方式传递到前台变成问号的处理
2017-01-09 【JS与数字转字符串】在Javascript中如何按位数截取小数