您的位置:首页 > 编程语言 > Java开发

java 实现 排列 组合

2013-02-06 16:38 501 查看
import java.util.ArrayList;

/**
*
*
* permutation and combination
*
* @author Administrator
*/
public class Pac {

Pac(String str) {
this.str = str;
}
String str;//源字符串。
String state;//c or a 状态
/*
* 组合数
*/

public void permutation(int c) {
state="a";
alc = new ArrayList<String>();
ala = new ArrayList<String>();
c(str, c);
for (String s : alc) {
a(s, c);
}System.out.println("共计" + ala.size() + "个 组合");
for (String s : ala) {
System.out.println(s);
}
System.out.println("共计" + ala.size() + "个 组合");
}
ArrayList<String> ala = new ArrayList<String>();//返回用的al

void a(String str, int c) {
filla(str, c, "");
}

void filla(String str, int c, String pre) {
if (c <= 0) {
System.out.println("选择的个数太少必须大于0当前是" + c);
return;
}
if (c == 1) {
ala.add(pre + str.charAt(0));
return;
}
for (int i = 0; i  < str.length(); i++) {
filla(str.substring(0, i) + str.substring(i + 1, str.length()), c - 1, pre + str.charAt(i));//正常
}

}

/*
* 排列数
*/
public void combination(int c) {
state="c";
alc = new ArrayList<String>();
c(str, c);
for (String s : alc) {
System.out.println(s);
}
System.out.println("共计" + alc.size() + "个 排列");
}
/*
* 内部组合
*/

private ArrayList<String> c(String str, int c) {
if (c > str.length()) {
System.out.println("数组内部出错选择大于数组长度");
return null;
}
fillc(str, c, "");
return null;
}
ArrayList<String> alc = new ArrayList<String>();//返回用的al

void fillc(String str, int c, String pre) {
if (c <= 0) {
System.out.println("选择的个数太少必须大于0当前是" + c);
return;
}
if (c == 1) {
for (char s : str.toCharArray()) {
alc.add(pre + s);
}
return;
}
fillc(str.substring(1, str.length()), c - 1, pre + str.charAt(0));//正常
//重填
if (c <= str.length() - 1) {
fillc(str.substring(1, str.length()), c, pre);
}
}

public static void main(String[] args) {
Pac p = new Pac("xyz");
//p.combination(3);
p.permutation(3);

}
}
。。。。。
vzw
wvz
wzv
zvw
zwv
vxy
vyx
xvy
xyv
yvx
yxv
vxz
vzx
xvz
xzv
zvx
zxv
vyz
vzy
yvz
yzv
zvy
zyv
wxy
wyx
xwy
xyw
ywx
yxw
wxz
wzx
xwz
xzw
zwx
zxw
wyz
wzy
ywz
yzw
zwy
zyw
xyz
xzy
yxz
yzx
zxy
zyx
共计15600个 组合
成功构建 (总时间: 5 秒)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: