字符串组合

 1 package test;
 2 import java.util.LinkedList;
 3 
 4 public class TestCombination {
 5     public static void combination(char[] arr) {
 6         int len = arr.length;
 7         int[] used = new int[len];
 8         LinkedList<Character> linkedlist = new LinkedList<Character>();
 9         combination(arr, 0, linkedlist, used);
10     }
11 
12     public static void combination(char[] arr, int i,
13             LinkedList<Character> linkedlist, int[] used) {
14         if (i == arr.length) {
15             for (int j = 0; j < linkedlist.size(); j++) {
16                 System.out.print(linkedlist.get(j) + " ");
17             }
18             System.out.println();
19         } else {
20             for (int k = 0; k < arr.length; k++) {
21                 if (used[k] == 0) {
22                     used[k] = 1;
23                     linkedlist.push(arr[k]);
24                     combination(arr, i + 1, linkedlist, used);
25                     linkedlist.pop();
26                     used[k] = 0;
27                 }
28             }
29         }
30     }
31     public static void combination_norepeat(String str){
32         char[] charr=str.toCharArray();
33         int [] used=new int[255];
34         int diffcharnum=0;
35         for(int i=0;i<charr.length ;i++){
36             used[charr[i]]++;
37         }
38         char[] res=new char[charr.length];
39         for(int i=0;i<255;i++){
40             if(used[i]>0){
41                 diffcharnum++;
42             }
43         }
44         char[] letters=new char[diffcharnum];  //统计不同的字符
45         for(int i=0,j=0;i<255&&j<diffcharnum;i++){
46             if(used[i]>0){
47                 letters[j++]=(char) i;
48             }
49         }
50         combination_norepeat(charr,0,used,res,letters);
51     }
52     public static void combination_norepeat(char [] str,int i,int [] used,char [] res,char[] letters){
53         if(i==res.length ){
54             for(int j=0;j<res.length;j++){
55                 System.out.print(res[j]+" ");
56             }
57             System.out.println();
58         }else{
59             for(int k=0;k<letters.length;k++){
60                 if(used[letters[k]]>0){
61                     used[letters[k]]--;
62                     res[i]=letters[k];
63                     combination_norepeat(str,i+1,used,res,letters);
64                     used[letters[k]]++;
65                 }
66             }
67         }
68     }
69     public static int AddWithoutArithmetic(int num1, int num2) {
70         if (num2 == 0)
71             return num1;
72         int sum = num1 ^ num2;
73         int carry = (num1 & num2) << 1;
74         return AddWithoutArithmetic(sum, carry);
75     }
76 
77     public static void main(String args[]) {
78         String str = "aabc";
79         combination_norepeat(str);
80     }
81 }
原文地址:https://www.cnblogs.com/waka401/p/2628703.html