递归——0-1 Knapsack

来源:互联网 发布:强迫症 知乎 编辑:程序博客网 时间:2024/06/02 04:12

最基础的0-1背包问题

题目:

Given a knapsack which can hold s pounds of items, and a set of items with weight w1, w2, ... wn. Returnwhether we can pick specific items so that their total weight s.

Example Input: s = 20; w = [14, 8, 7, 5, 3]; 

Example Output: true.


分析:

依照递归的三个步骤:

(1). 找出 base case

当前目标重量为0时,我们就不再需要从knapsack中找item了,证明可以满足要求并返回true;

当前目标重量小于0,knapsack中剩余的item不需要再判断了,失败并返回false;

knapsack中所有的item都判断过了,仍然不能满足s(s != 0),证明失败并返回false;

(2). 分析出 recursion rule

在递归函数中,对于knapsack中的任一item,我们可以选择或者不选择它。

当不选择当前item时,目标重量仍然为当前的 s,子递归函数开始判断下一个 item;

当选择当前item时,目标重量需要减掉当前item的重量即变成了 s - weight(current item),子递归函数开始判断下一个item;

(3). 确定递归函数的参数

首先我们需要有item重量的数组 w;

我们需要一个 int参数 记录当前目标重量 s;

需要一个 int参数,记录当前正在判断的 item id 或是 item index。


代码:

public class Knapsack {    public static void main(String[] args) {        int s = 20;        int[] weights = {14, 8, 7, 5, 3};        System.out.println(Knapsack(weights, s, 0));    }    public static boolean Knapsack(int[] weights, int s, int index) {        if (s == 0)            return true;        if (s < 0 || index == weights.length)            return false;        // skip or select the index item        return Knapsack(weights, s, index+1) || Knapsack(weights, s-weights[index], index+1);    }}



1 0
原创粉丝点击