一个数组中是否存在和为一个指定值,递归回溯解决

求取一个数组中所有的数字组合(和为目标数字)

1.对于一个数组类似:[1,2,3,4,7],寻找可以重复使用每一个数字,组成的集合为目标数7的组合集合。如:
[
[1,1,1,1,1,1,1],
[2,2,2,1],
[3,4],
[3,3,1],
…]
]
使用回溯进行解决,需要注意,原数组数字不可重复。

class Solution{
	private List<List<Integer>> ans = new ArrayList<>();
	private List<Integer> combaine = new ArrayList<>();
	public List<List<Integer>> re(int[] candaines, int target){
		
	}
	private void dfs(int[] candaines, int target, int idx){
		//到达数组边界返回
		if(idx == candaines.length){
			return;
		}
		//满足条件返回
		if(target == 0){
			ans.add(new ArrayList<Integer>(combaine));
			return;
		}
		dfs(candaines, target, idx+1);
		if(target - candaines[idx] >=0){
			combaine.add(candaines[idx]);
			//由于一个数可以重复取,这里idx不加一
			dfs(candaines, target - candaines[idx], idx);
			combaine.remove(combaine.size() - 1);
		}
	}
}

2.同样对于一个数组[1,1,3,2,4],存在重复的数字,每个数字只能用一次。不妨考虑首先对这个数组进行处理,让它不存在重复的数字。可以先进行排序,后将一个重复的数记下它的出现次数。

class Solution {
    List<int[]> freq = new ArrayList<int[]>();
    List<List<Integer>> ans = new ArrayList<List<Integer>>();
    List<Integer> sequence = new ArrayList<Integer>();

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        //排序
        Arrays.sort(candidates);
        //处理数组
        for (int num : candidates) {
            int size = freq.size();
            if (freq.isEmpty() || num != freq.get(size - 1)[0]) {
                freq.add(new int[]{num, 1});
            } else {
                ++freq.get(size - 1)[1];
            }
        }
        dfs(0, target);
        return ans;
    }

    public void dfs(int pos, int rest) {
    	//符合条件返回
        if (rest == 0) {
            ans.add(new ArrayList<Integer>(sequence));
            return;
        }
        //越界返回
        if (pos == freq.size() || rest < freq.get(pos)[0]) {
            return;
        }

        dfs(pos + 1, rest);
        //这是target可以容纳的当前数的个数
        //如果这个数不重复,那么most挺好的2233
        int most = Math.min(rest / freq.get(pos)[0], freq.get(pos)[1]);   //根据次数加和减
        for (int i = 1; i <= most; ++i) {
            sequence.add(freq.get(pos)[0]);
            dfs(pos + 1, rest - i * freq.get(pos)[0]);
        }
        for (int i = 1; i <= most; ++i) {
            sequence.remove(sequence.size() - 1);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值