abc字符串的排列組合--java版

1.概述

        在高中的時候常常會遇到一些排列組合的問題,那個時候基本上都是基於公式計算的。其實理論上是能夠枚舉出來的,而計算機最擅長的事情就是枚舉,本文主要討論a,b,c三個字符的各類排列組合問題,當字符增長的時候,思路是相同的。java

2.可重複排列

        可重複排列就是給定,a,b,c三個字符,組成長度爲3的字符串,其中a,b,c可使用屢次。這個時候可使用遞歸思想:第一個字符從a,b,c中選擇一個,以後的問題轉化爲:a,b,c三個字符組成長度爲2的字符串。控制好遞歸退出的條件,便可。bash

public class Permutation {
    public static void main(String[] args) {
        char[] chs = {'a', 'b', 'c'};
        per(new char[3], chs, 3 - 1);
    }

    public static void per(char[] buf, char[] chs, int len) {
        if (len == -1) {
            for (int i = buf.length - 1; i >= 0; --i) {
                System.out.print(buf[i]);
            }
            System.out.println();
            return;
        }
        for (int i = 0; i < chs.length; i++) {
            buf[len] = chs[i];
            per(buf, chs, len - 1);
        }
    }
}
複製代碼


3.全排列

        全排列的意思,就是隻能用a,b,c三個元素,作排列,每一個用且只能用一次。spa

        也能夠利用遞歸,第一個字符串一共有n種選擇,剩下的變成一個n-1規模的遞歸問題。而第一個字符的n種選擇,都是字符串裏面的。所以可使用第一個字符與1-n的位置上進行交換,獲得n種狀況,而後遞歸處理n-1的規模,只是處理完以後須要在換回來,變成原來字符的樣子。
code

public class Permutations {
    public static void main(String[] args) {
        char[] arrs = {'a','b','c'};
        List<List<Character>> results = new Permutations().permute(arrs);
        for (List<Character> tempList : results){
            System.out.println(String.join(",",
                    tempList.stream().map(s->String.valueOf(s)).collect(Collectors.toList())));
        }
    }

    public List<List<Character>> permute(char[] nums) {
        List<List<Character>> lists = new LinkedList<>();
        tempPermute(nums, 0, lists);
        return lists;
    }

    public void tempPermute(char[] nums, int start, List<List<Character>> lists){
        int len = nums.length;
        if(start == len-1){
            List<Character> l = new LinkedList<>();
            for(char num : nums){
                l.add(num);
            }
            lists.add(l);
            return;
        }
        for(int i=start; i<len; i++){
            char temp = nums[start];
            nums[start] = nums[i];
            nums[i] = temp;
            tempPermute(nums, start+1, lists);
            temp = nums[start];
            nums[start] = nums[i];
            nums[i] = temp;
        }
    }
}複製代碼

在1中使用打印的方式,這裏使用返回值的方式,由於有些場景咱們但願獲得值而且返回。遞歸


4.組合

      求全部組合也就是abc各個位是否選取的問題,第一位2中可能,第二位2種。。。因此一共有2^n種。用0表示不取,1表示選取,這樣能夠用110這樣的形式表示ab。abc一共的表示形式從0到2^3-1。而後按位與運算,若是結果爲1就輸出當前位,結果0不輸出。
字符串

public class Comb {
	public static void main(String[] args) {
		char[] chs = {'a','b','c'};
		comb(chs);
	}
 
	public static void comb(char[] chs) {
		int len = chs.length;
		int nbits = 1 << len;
		for (int i = 0; i < nbits; ++i) {
			int t;
			for (int j = 0; j < len; j++) {
				t = 1 << j;
				if ((t & i) != 0) { // 與運算,同爲1時纔會輸出
					System.out.print(chs[j]);
				}
			}
			System.out.println();
		}
	}
}複製代碼
相關文章
相關標籤/搜索