排列、组合例子

可以直接复制运行一下

排列的例子

 

public class ListChars
{
     /**
     * @param chars 总的字符序列(数组)
     * @param n     要取出的字符的个数
     */
    public static void doit(char[] chars, int n) {
        if (n <= 0 || chars == null) {
            return;
        }
        List<Character> charList = new ArrayList<>();
        //通过这一步初始化序列的长度
        for (int i = 0; i < n; i++) {
            charList.add('#');
        }
        listAll(charList, chars, n);
    }

    /**
     * 从m个元素中任取n个并对结果进行全排列
     * @param list   用于承载可能的排列情况的List
     * @param chars  总的字符数组,长度为m
     * @param n      从中取得字符个数
     */
    public static void listAll(List<Character> list, char[] chars, int n) {
        if (n == 0) {
            //这里偷懒,直接打印了....
            System.out.println(list);                   // 输出一种可能的排列
            return;
        }
        for (char aChar : chars) {                      // 暴力尝试
            if (!list.contains(aChar)) {                // 若List中不包含这一位元素
                list.set(list.size() - n, aChar);       // 将当前元素加入
            } else {                                    // 否则跳到下一位
                continue;
            }
            listAll(list, chars, n - 1);                // 下一个位置
            list.set(list.size() - n, '#');             // 还原
        }
    }

    public static void main(String[] args) {
        //  以字符数组承载总的字符集合
        char[] chars = {'a', 'b', 'c', 'd', 'e'};
        ListChars.doit(chars, 2);
    }
    
    
}

组合的例子

public class Combine {  
    private static ArrayList <Integer>tmpArr = new ArrayList<>();  
    public static void main(String[] args) {  
        int [] com = {1,2,3,4,5};  
        int k = 3;    
        if(k > com.length || com.length <= 0){  
            return ;  
        }  
        combine(0 ,k ,com);  
    }  
    public static void combine(int index,int k,int []arr) {  
        if(k == 1){  
            for (int i = index; i < arr.length; i++) {  
                tmpArr.add(arr[i]);  
                System.out.println(tmpArr.toString());  
                tmpArr.remove((Object)arr[i]);  
            }  
        }else if(k > 1){  
            for (int i = index; i <= arr.length - k; i++) {  
                tmpArr.add(arr[i]);  
                combine(i + 1,k - 1, arr);  
                tmpArr.remove((Object)arr[i]);  
            }  
        }else{  
            return ;   
        }  
    }  
}  

 

posted @ 2017-12-18 14:31  钓鱼翁  阅读(672)  评论(0编辑  收藏  举报