java 字符數字組合算法

從指定集合中獲取元素組合成不同的字符串.

 

  • 組合生成類(Combination.java)

 

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

 

/**

 * 

 * @author hymanz [email protected]

 *

 */

public class Combination {

 

    private char[] base;

 

    public Combination(char[] base) {

        this.base = base;

    }

 

    public List<char[]> getCombinations(int length) {

 

        List<char[]> list = new ArrayList<char[]>();

        list.add(new char[length]);

 

        return compose(0, list);

    }

 

    private List<char[]> compose(int index, List<char[]> list) {

 

        if (index >= list.get(0).length) {

            return list;

        }

 

        for (int i = 0, size = list.size(); i < size; i++) {

            char[] item = list.get(i);

            for (int j = 0; j < base.length; j++) {

                if (j > 0) {

                    item = copy(item);

                    list.add(item);

                }

                item[index] = base[j];

            }

        }

 

        return compose(++index, list);

    }

 

    private char[] copy(char[] item) {

        return Arrays.copyOf(item, item.length);

    }

 

}

 

  • 調用方式 

public class Main {

    public static void main(String[] args) {

        char[] base = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

        

        Combination combination = new Combination(base);

        List<char[]> result = combination.getCombinations(3);

        

        for (char[] cs : result) {

            System.out.println( new String(cs));

        }

    }

}

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章