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

排序:

方法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;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值