- package test;
- import java.util.Random;
- /**
- * 编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符,例如(这只是个特例):
- * 原始字符串是"abc",打印得到下列所有组合情况:
- * "a" "b" "c"
- * "ab" "bc" "ca" "ba" "cb" "ac"
- * "abc" "acb" "bac" "bca" "cab" "cba"
- *
- * @author live-dream
- *
- */
- public class Test003 {
-
- public static void main(String[] args) {
- String s = "abcde";
- int n = s.length();
-
- for(int i=1; i<=n; i++){
- int[][] permutations = permutationResults(n,i);
-
- for(int j=0; j<permutations.length; j++){
- print(s,permutations[j]);
- }
- System.out.println();
- }
- }
-
- public static int[][] permutationResults(int n,int r){
- int[][] permutations = null;
- int resultCount = 0;
- int molecule = 1;
- int denominator = 1;
-
- for(int i=1; i<=n; i++){
- molecule *= i;
- }
-
- for(int i=1; i<=n-r; i++){
- denominator *= i;
- }
-
- resultCount = molecule/denominator;
- permutations = new int[resultCount][r];
-
- Random random = new Random();
- for(int i=0; i<permutations.length; i++){
-
- for(int j=0; j<permutations[i].length; j++){
- int rand = random.nextInt(n);
-
- if(j==0)
- permutations[i][j] = rand;
-
- if(j>0){
- boolean isSave = saveEle_no_repeat(permutations[i],j,rand);
- if(!isSave)
- j--;
- }
- }
-
- if(i>0){
- boolean isSave = saveArr_no_repeat(permutations, i,permutations[i]);
- if(!isSave)
- i--;
- }
- }
-
- return permutations;
- }
-
- public static boolean saveEle_no_repeat(int[] permutation, int index, int value){
- boolean isSave = true;
- for(int i=0; i<index; i++){
- if(permutation[i]==value){
- isSave = false;
- break;
- }
- }
-
- if(isSave)
- permutation[index] = value;
-
- return isSave;
- }
-
- public static boolean saveArr_no_repeat(int[][] permutations, int index, int[] permutation){
- boolean isSave = false;
- for(int i=0; i<index; i++){
- isSave = false;
- for(int j=0; j<permutations[i].length; j++){
- if(permutations[i][j]!=permutation[j])
- isSave = true;
- }
-
- if(!isSave)
- break;
- }
- //
- // if(isSave)
- // permutations[index] = permutation;
-
- return isSave;
- }
-
- public static void print(String s, int[] arr){
- String result = "";
- for(int i=0; i<arr.length; i++){
- result += s.charAt(arr[i]);
- }
- System.out.print("\""+result+"\"");
- }
- }
复制代码 |