{a, b, c}
要求生成长度为N的排列算法。
如长度为2:
[a, a]
[a, b]
[a, c]
[b, a]
[b, b]
[b, c]
[c, a]
[c, b]
[c, c]
[b]问题补充:[/b]
对递归总是模模糊糊的感觉...
我知道这个应该用递归,可是就是找不到一个可行的方案。
楼下的其他语言就让我更不明白了...算法么,还是接近C的好吧,大家看的是思路。
[b]问题补充:[/b]
这个算法能把递归改成非递归么~
求一可重复排列算法
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
6条回答 默认 最新
- lcf2025 2009-09-23 10:29关注
抛个砖头,提供个思路
[code="java"]
public class testList {private int listLength; //生成排列的长度 private List<Integer> sourceList;//源数据 private List<List<Integer>> targetList;//生成的所有排列存放的容器 public testList(int listLength,List<Integer> sourceList) { this.listLength = listLength; this.sourceList = sourceList; this.targetList = new LinkedList<List<Integer>>(); } /** * @param args */ public static void main(String[] args) { List<Integer> sourceList = new ArrayList<Integer>(); for(int i=1;i<3;i++) { sourceList.add(i); } testList tl = new testList(4,sourceList); List<List<Integer>> targetList = tl.productList(); System.out.println(targetList.size()); for(int i=0;i<targetList.size();i++) { System.out.println(Arrays.toString(targetList.get(i).toArray())); } } public List<List<Integer>> productList() { if(listLength>0) { for(int i=0;i<sourceList.size();i++) { List<Integer> childList = new LinkedList<Integer>(); addEle(childList,i); } } return this.targetList; } private void addEle(List<Integer> currentList,int index) { currentList.add(sourceList.get(index)); if(currentList.size()<listLength) { for(int i=0;i<sourceList.size();i++) { List<Integer> childList = new LinkedList<Integer>(); childList.addAll(currentList); addEle(childList,i); } }else if(currentList.size()==listLength) { targetList.add(currentList); } }
}
[/code]
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 如何在炒股软件中,爬到我想看的日k线
- ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
- ¥15 seatunnel 怎么配置Elasticsearch
- ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
- ¥15 (标签-MATLAB|关键词-多址)
- ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
- ¥500 52810做蓝牙接受端
- ¥15 基于PLC的三轴机械手程序
- ¥15 多址通信方式的抗噪声性能和系统容量对比
- ¥15 winform的chart曲线生成时有凸起