leetCode No.416 Partition Equal Subset Sum

来源:互联网 发布:latex 算法伪代码 编辑:程序博客网 时间:2024/05/18 11:47

题目

Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.

Note:
Both the array size and each of the array element will not exceed 100.

Example 1:

Input: [1, 5, 11, 5]Output: trueExplanation: The array can be partitioned as [1, 5, 5] and [11].

Example 2:

Input: [1, 2, 3, 5]Output: falseExplanation: The array cannot be partitioned into equal sum subsets.

标签:Dynamic Programming

题意

给定一个非空的只包含正整数的数组,判断是否能将该数组分为两个子集。这两个子集中所有元素的加和相等。

解题思路

如果一个数组可以按照题意分为两个子集,那么每一个子集的和一定等于数组所有数总和的一半。这时这个问题就可以视为一个背包问题,也是背包恰好装满问题:有一个背包,最多能装w重量的物品,有s个物品,每个物品的重量是weights[i]。在s个物品中取任意个使得背包正好装满。
换句话说,在本题中这个问题就变成了,在整个数组中找任意个数,这些数的加和恰好等于数组中数总和的一半。上文中的w是本题中的数组总和的一半,s是数组长度,weights即为nums数组。

代码

public class Solution {    public boolean canPartition(int[] nums) {        int sum = 0;        for (int i : nums) {            sum += i;        }        if (sum % 2 != 0) {            return false;        }        int half = sum / 2;        return kp(half, nums.length, nums );    }    public boolean kp(int w, int s,int[] nums) {        if (w == 0) {            return true;        }        if (w < 0 || w > 0  && s == 0) {            return false;        }        if (kp(w - nums[s - 1], s - 1, nums)) {            return true;        }        return kp(w, s - 1,nums);    }}

相关链接

原题
源代码(github)

0 0
原创粉丝点击