Java实现数组元素的排列组合

来源:互联网 发布:华中科技大学软件下载 编辑:程序博客网 时间:2024/05/21 17:31

组合

组合是非递归实现的(有Bug,没有输出所以的组合)

package D919;import java.util.ArrayList;import java.util.List;public class Combine {    public static List<List<Integer>> sub(int[] a) {        int n = a.length;        List<List<Integer>> result = new ArrayList<List<Integer>>();        for (int i = 0; i < n; i++) {            for (int j = i; j < n; j++) {                List<Integer> list = new ArrayList<>();                for (int k = i; k <=j; k++) {                    list.add(a[k]);                }                result.add(list);            }        }        return result;    }    public static void main(String[] args) {        int[] a = {1, -2, 4, 8, -4, 7, -1, -5};        System.out.println(sub(a));    }}

递归实现

package D920;import java.util.ArrayList;import java.util.List;public class Combine {    static List<String> list = new ArrayList<>();    public static void sub(String s) {        char[] chars = s.toCharArray();        StringBuffer sb = new StringBuffer("");        for (int i = 1; i <= chars.length; i++) {            sub(chars, 0, i, sb);        }    }    private static void sub(char[] c, int begin, int len, StringBuffer sb) {        if (len == 0) {            list.add(String.valueOf(sb));            return;        }        if (begin == c.length) {            return;        }        sb.append(c[begin]);        sub(c, begin + 1, len - 1, sb);        sb.deleteCharAt(sb.length() - 1);        sub(c, begin + 1, len, sb);    }    public static void main(String[] args) {        String s = "abc";        sub(s);        System.out.println(list);    }}

排列

排列是递归实现的

package D919;public class Permute {    public void permutation(int[] a, int length, int index) {        if (index == length) {            for (int i = 0; i < length; i++) {                System.out.print(a[i] + " ");            }            System.out.println();        } else {            for (int i = index; i < length; i++) {                if (isSwap(a, length, i)) {                    swap(a, index, i);                    permutation(a, length, index + 1);                    swap(a, index, i);                }            }        }    }    private boolean isSwap(int[] a, int length, int index) {        for (int i = index + 1; i < length; i++) {            if (a[index] == a[i]) {                return false;            }        }        return true;    }    private void swap(int[] a, int index, int i) {        int temp = a[index];        a[index] = a[i];        a[i] = temp;    }    public static void main(String[] args) {        int[] b = {1, 2, 3};        new permute().permutation(b, b.length, 0);    }}
阅读全文
0 0
原创粉丝点击