字符串的排列
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 结果请按字母顺序输出。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | public ArrayList<String> Permutation(String str) { ArrayList<String> result = new ArrayList<String>(); if (str == null || str.length() > 9 || str.length()== 0 ) { return result; } str = str.trim(); Permutation(str.toCharArray(), 0 , result); // HashSet<String> hs = new HashSet<String>(result); //此仅去重,没有字典序排列,可能错误 // new ArrayList<String>(hs); Collections.sort(result); //字典序排列 有些oj要求 return result; } public static void Permutation( char [] data, int beginIdx,ArrayList<String> result) { if (beginIdx == data.length) { result.add( new String(data)); } else { for ( int i = beginIdx; i < data.length; ++i) { //有重复字符时,跳过 if (i!=beginIdx && data[i]==data[beginIdx]) continue ; //当i==begin时,也要遍历其后面的所有字符; //当i!=begin时,先交换,使第begin位取到不同的可能字符,再遍历后面的字符 char temp = data[beginIdx]; data[beginIdx] = data[i]; data[i] = temp; Permutation(data, beginIdx + 1 , result); //为了防止重复的情况,还需要将begin处的元素重新换回来 恢复打扫战场,恢复为原来子串, data共享 temp = data[beginIdx]; data[beginIdx] = data[i]; data[i] = temp; /* 举例来说“b(acd)” acd排列 ,为什么使用了两次swap函数? 函数栈变化恢复 , "acd第一次输出 cda后,完全退栈 返回data应该还是acd" 交换栈 退栈 bacd bacd bcad bcad bcda 打印 -> bcda */ } } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构