排列数组所有情况
以下为转载内容
package java1030;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class Test1423 {
public static void main(String[] args){
String[] a = {"1","2","3"};
display(Arrays.asList(a),"");
}
public static void display(List list, String str){
if(!(str.equals(""))){
System.out.println(str);
}
for (int i = 0, length = list.size();i < length; i++){
List temp = new LinkedList(list);
display(temp,str + temp.remove(i));
}
}
}
我们把list简单的表达为括号加具体元素,比如(1,2,3)
传入list为(1,2,3)
display((1,2,3),"")
i=0
remove(0)
display((2,3),"1")
i=1
remove(1)
display((1,3),"2")
i=2
remove(2)
display((1,2),"3")
这一步把display((1,2,3),"")分成了三个方法
display((2,3),"1")
display((1,3),"2")
display((1,2),"3")
并输出了"1","2","3"
第一个方法:display((2,3),"1")
i=0
remove(0)
display((3),"12")
i=1
remove(1)
display((2),"13")
第二个方法:display((1,3),"2")
i=0
remove(0)
display((3),"21")
i=1
remove(1)
display((1),"23")
第三个方法:display((1,2),"3")
i=0
remove(0)
display((2),"31")
i=1
remove(1)
display((1),"32")
这一步把三个方法变成6个方法
display((3),"12")
display((2),"13")
display((3),"21")
display((1),"23")
display((2),"31")
display((1),"32")
并输出了"12","13","21","23","31","32"
最好这6个方法再输出
"123","132","213","231","312","321"
当然,顺序不是这样,要先遍历到底再回去的,所以是
1 12 123 13 132
2 21 213 23 231
3 31 312 32 321
当然也可以排列出单单三个数字的情况
display方法加上这一句即可
if(str.length()==3){
System.out.println(str);
}
这样输出就是
123 132 213 231 312 321