39. Combination Sum

这类题太多了,换零钱,寻找多少个数和为定值,大同小异。

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (candidates == null || candidates.length == 0) {
            return res;
        }
        List<Integer> l = new ArrayList<Integer>();
        Arrays.sort(candidates);
        solve(candidates, 0, target, res, l);
        return res;
    }
    
    public void solve(int[] a, int j, int target, List<List<Integer>> res, List<Integer> l) {
        if (target == 0) {
            List<Integer> temp = new ArrayList<Integer>(l);
            res.add(temp);
            return;
        }
        for (int i = j; i < a.length; i++) {
            if (a[i] > target) {
                return;
            }
            l.add(a[i]);
            solve(a, i, target - a[i], res, l);
            l.remove(l.size() - 1);
        }
    }
}

顺便统计解的个数:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test {

	public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
		List<List<Integer>> res = new ArrayList<List<Integer>>();
		if (candidates == null || candidates.length == 0) {
			return res;
		}
		List<Integer> l = new ArrayList<Integer>();
		Arrays.sort(candidates);
		System.out.println(solve(candidates, 0, target, res, l));
		return res;
	}

	public static int solve(int[] a, int j, int target, List<List<Integer>> res, List<Integer> l) {
		int c = 0;
		if (target < 0) {
			return 0;
		}
		if (target == 0) {
			List<Integer> temp = new ArrayList<Integer>(l);
			res.add(temp);
			return 1;
		}
		int prev = -1;
		for (int i = j; i < a.length; i++) {
			if (prev != a[i]) {
				l.add(a[i]);
				c += solve(a, i + 1, target - a[i], res, l);
				l.remove(l.size() - 1);
				prev = a[i];
			}
		}
		return c;
	}

	public static void main(String[] args) {
		int[] a = {10, 1, 2, 7, 6, 1, 5};
		combinationSum2(a, 8);
	}

}


第二种写法:

public class Problem_01_CoinsWay {

	public static int coins1(int[] arr, int aim) {
		if (arr == null || arr.length == 0 || aim < 0) {
			return 0;
		}
		return process1(arr, 0, aim);
	}

	public static int process1(int[] arr, int index, int aim) {
		int res = 0;
		if (index == arr.length) {
			res = aim == 0 ? 1 : 0;
		} else {
			for (int i = 0; arr[index] * i <= aim; i++) {
				res += process1(arr, index + 1, aim - arr[index] * i);
			}
		}
		return res;
	}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值