{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]
这个算法能把递归改成非递归么~
抛个砖头,提供个思路
[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]
Scala版:4行搞定
[quote]
scala> def listT :List[List[T]] = {
| if(len == 0) List(Nil)
| else for(x <- ls;xs <- list(ls,len-1)) yield x::xs
| }
list: TList[List[T]]
scala> list(List('a','b','c'),2)
res2: List[List[Char]] = List(List(a, a), List(a, b), List(a, c), List(b, a),List(b, b), List(b, c), List(c, a), List(c, b), List(c, c))[/quote]
ruby 版 ……:
[code="ruby"]def product as, bs
as.map{|a| bs.map{|b| [*a,b]}}.flatten 1
end
s = %w[a b c]
2.times.inject([[]]){|acc, _|product acc, s}[/code]
:x Ruby... 真强大
:cry: 误上java贼船的泪奔过~~~~~~
记得 scala 可以在编译期把很多递归展开成循环的。
而 ruby 的就是非递归的 ……
改写成类 C 的太繁琐,懒得写 ……
用同样的思路,用C++或Java在10行之类应该也可以搞定