求所有可能排序与所有可能子序列

来源:互联网 发布:旅行商问题的退火算法 编辑:程序博客网 时间:2024/06/05 09:10

排序:

方法1:非递归

建立空结果集,遍历数组所有数据,不断将数据插入到结果集中每个结果项的所有位置。

    public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {        HashMap<ArrayList<Integer>, Integer> map = new HashMap<ArrayList<Integer>, Integer>();        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();        res.add(new ArrayList<Integer>());        for (int i = 0; i < num.length; i++) {        ArrayList<ArrayList<Integer>> tmp = new ArrayList<ArrayList<Integer>>();        for (ArrayList<Integer> item : res) {        for (int k = 0; k < item.size() + 1; k++) {        item.add(k, num[i]);        if (!map.containsKey(item)) {        tmp.add(new ArrayList<Integer>(item));        map.put(new ArrayList<Integer>(item), 1);        }        item.remove(k);        }        }        res = new ArrayList<ArrayList<Integer>>(tmp);        map.clear();        }        return res;    }
方法2:递归

不断地将当前起始位置的值与之后的任意位置交换

public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();HashMap<ArrayList<Integer>, Integer> map = new HashMap<ArrayList<Integer>, Integer>();worker(num, 0, res, map);return res;}private void worker(int[] num, int lo, ArrayList<ArrayList<Integer>> res, HashMap<ArrayList<Integer>, Integer> map) {if (lo >= num.length) {ArrayList<Integer> item = addToList(num);if (!map.containsKey(item)) {res.add(item);map.put(item, 1);}}for (int i = lo; i < num.length; i++) {swap(num, lo, i);worker(num, lo + 1, res, map);swap(num, lo, i);}}private ArrayList<Integer> addToList(int[] num) {ArrayList<Integer> res = new ArrayList<Integer>();for (int i : num) {res.add(i);}return res;}private void swap(int[] num, int i, int j) {int tmp = num[i];num[i] = num[j];num[j] = tmp;}

所有可能子字符串:

位思想,数组每个元素对应一位,如abc,分别对应001, 010, 100。abc 3个字符共对应2^3-1个可能子序列(去掉空字符串这一特殊情况,对应0),从1到2^3-1循环,分别与001,010,100按位与,不为0说明对应字符在子序列中。

public ArrayList<String> sub(char[] str) {ArrayList<String> res = new ArrayList<String>();StringBuilder sb = new StringBuilder();for (int i = 1, total = (1 << str.length) - 1; i <= total; i++) {sb.setLength(0);for (int j = 0; j < str.length; j++) {if ((i & (1 << j)) != 0) {sb.append(str[j]);}}res.add(sb.toString());}return res;}


0 0
原创粉丝点击