列出字符串所有组合
2012-08-28 17:05
148 查看
import java.math.BigInteger; import java.util.*; import java.io.*; public class Demo { private int[] a; private BigInteger numLeft; private BigInteger total; public Demo(int n) { if (n < 1) { throw new IllegalArgumentException("Min 1"); } a = new int ; total = getFactorial(n); reset(); } public void reset() { for (int i = 0; i < a.length; i++) { a[i] = i; } numLeft = new BigInteger(total.toString()); } public BigInteger getNumLeft() { return numLeft; } public BigInteger getTotal() { return total; } public boolean hasMore() { return numLeft.compareTo(BigInteger.ZERO) == 1; } private static BigInteger getFactorial(int n) { BigInteger fact = BigInteger.ONE; for (int i = n; i > 1; i--) { fact = fact.multiply(new BigInteger(Integer.toString(i))); } return fact; } public int[] getNext() { if (numLeft.equals(total)) { numLeft = numLeft.subtract(BigInteger.ONE); return a; } int temp; // Find largest index j with a[j] < a[j+1] int j = a.length - 2; while (a[j] > a[j + 1]) { j--; } // Find index k such that a[k] is smallest integer // greater than a[j] to the right of a[j] int k = a.length - 1; while (a[j] > a[k]) { k--; } // Interchange a[j] and a[k] temp = a[k]; a[k] = a[j]; a[j] = temp; // Put tail end of permutation after jth position in increasing order int r = a.length - 1; int s = j + 1; while (r > s) { temp = a[s]; a[s] = a[r]; a[r] = temp; r--; s++; } numLeft = numLeft.subtract(BigInteger.ONE); return a; } //程序测试入口 public static void main(String[] args) { int[] indices; String[] elements = {"喔", "呼", "喂", "完", "哇", "哈"}; Demo x = new Demo(elements.length); StringBuffer permutation; File file = new File("1.txt"); PrintStream ps = null; try { ps = new PrintStream(file); } catch (Exception e) { e.printStackTrace(); } System.setOut(ps); while (x.hasMore()) { permutation = new StringBuffer("%"); indices = x.getNext(); for (int i = 0; i < indices.length; i++) { permutation.append(elements[indices[i]]).append("%"); } //输出到1.txt文件中 System.out.println(permutation.toString()); } } }
相关文章推荐
- 有一个纯字符串,编写一段代码,列出其所有字符的大小写组合 如 :字符串“ji”,字母组合['ji','jI','Ji','JI'] 即每个字符的大小写组合
- 输入一串不重复的字符串,列出所有可能的组合(java实现)
- 编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符,例如: 原始字符串是"abc",打印得到下列所有组合情况
- java练习: 编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符,例如:
- 给定一个数字字符串,返回数字可能表示的所有可能的字母组合。数字与字母的对应关系和手机按键对应
- 找字符串的所有组合
- 输出该字符串中字符的所有组合
- 打印出一个字符串的所有组合的递归方式
- 【面试系列】编写一个程序,列出1-19所有相加为20的组合
- 求集合/字符串中的所有组合 (C语言)
- sql中删除冗余数据和一个叫department的表,里面只有一个字段name,一共有4条纪录,分别是a,b,c,d,对应四个球对,现在对列出所有组合等sql面试题
- 使用Microsoft Visual Studio International Pack获得中文字符串的所有拼音组合(处理多音字)
- 输出字符串的所有排列组合
- 读取一个字符串,输出它里面字符的所有组合
- 输入一个字符串,输出该字符串中字符的所有组合
- 字符串中字符的所有组合(组合中的先后顺序不考虑)
- 【一些题】打印字符串的所有组合
- 输入一个字符串,输出该字符串中字符的所有组合
- 回溯法 已知两个非负整数n和k(n>=k),列出集合S={a1,a2,~,an}的所有k组合
- c# 组合字符串组成密码的所有可能