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

用1、2、3、3、4、5这六个数字,用java写一个程序,打印出所有不同的排列 要求:"4"不能在第三位,"3"与"5"不能相连。

2011-06-29 10:50 1326 查看
package testWork;

/**
*
* 用1、2、2、3、4、5这六个数字,用java写一个程序,打印出所有不同的排列
* 如:512234、412345等,要求:"4"不能在第三位,"3"与"5"不能相连。
*
* @author  user
* @version  [版本号, Jun 29, 2011]
* @see  [相关类/方法]
* @since  [产品/模块版本]
*/
public class Test1
{
private int[] numbers = new int[] {1, 2, 3, 3, 4, 5};

public int n;

private String lastResult = "";

private boolean validate(String s)
{
if (s.compareTo(lastResult) <= 0) //按字典顺序比较两个字符串。
{
return false;
}
if (s.charAt(2) == '4')//"4"不能在第三位
{
return false;
}
if (s.indexOf("35") >= 0 || s.indexOf("53") >= 0)//"3"与"5"不能相连
{
return false;
}
return true;
}
/**
* <一句话功能简述>
* <功能详细描述>
* @param index
* @param result [参数说明]
*
* @return void [返回类型说明]
* @exception throws [违例类型] [违例说明]
* @see [类、类#方法、类#成员]
*/
public void list(String index, String result)
{
for (int i = 0; i < numbers.length; i++)
{
if (index.indexOf(i+48) < 0)
{
String s = result + String.valueOf(numbers[i]);
if (s.length() == numbers.length)
{
if (validate(s))
{
System.out.println(s);
lastResult = s;
n++;
}
break;
}
list(index + String.valueOf(i), s);
}
}
}
/**
* 主程序入口
* <功能详细描述>
* @param args [参数说明]
*
* @return void [返回类型说明]
* @exception throws [违例类型] [违例说明]
* @see [类、类#方法、类#成员]
*/
public static void main(String[] args)
{
Test1 t = new Test1();
t.list("", "");
System.out.println("总数:" + t.n);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐