赞
踩
- package com.algorithm.dynamicprogramming;
-
- /**
- * 题目描述:将一个正整数数组拆分成两个相同的子数组,如果能,返回true,如果不能返回false。
- *
- * Input: [1, 5, 11, 5]
- *
- * Output: true
- *
- * Explanation: The array can be partitioned as [1, 5, 5] and [11].
- *
- *
- * Input: [1, 2, 3, 5]
- *
- * Output: false
- *
- * Explanation: The array cannot be partitioned into equal sum subsets.
- *
- * @author rich
- *
- */
- public class PartitionEqualSubsetSum {
-
- public static void main(String[] args) {
- int[] arrs = new int[] {1, 5, 11, 5};
- System.out.println(partitionEqualSubsetSum(arrs));
- }
-
- /**
- * 算法分析:理论是就是将子数组是否等于sum/2
- * @param arrs
- * @return
- */
- public static boolean partitionEqualSubsetSum(int[] arrs) {
- if (arrs.length < 2) return false;
- int sum = 0;
- for (int i = 0; i < arrs.length; i++) {
- sum += arrs[i];
- }
- if (sum % 2 != 0) return false;
- return partitionEqualSubsetSum(arrs.length-1,arrs,sum/2);
- }
-
- /**
- * 递归方法
- * @param n
- * @param arrs
- * @param k
- * @return
- */
- public static boolean partitionEqualSubsetSum(int n,int[] arrs,int k) {
- if (k == 0) return true;
- if (n == 0 && arrs[n] == k) return true;
- else if (n == 0 && arrs[n] != k) return false;
- if (arrs[n] > k) return false;
- return partitionEqualSubsetSum(n-1,arrs,k) || partitionEqualSubsetSum(n-1,arrs,k-arrs[n]);
- }
-
- /**
- * 循环
- * @param n
- * @param arrs
- * @param k
- * @return
- */
- public static boolean partitionEqualSubsetSum(int[] arrs,int k) {
- // 初始化状态数组
- boolean[][] memo = new boolean[arrs.length][k+1];
- // 初始化状态
- for (int i = 0;i<arrs.length;i++) {
- memo[i][0] = true;
- }
-
- for (int i = 0;i<k+1;i++) {
- memo[0][i] = false;
- }
-
- memo[0][arrs[0]] = true;
-
- for (int i = 1;i<arrs.length;i++) {
- for (int j = 1;j<k+1;j++) {
- if (arrs[i]>j) { //
- memo[i][j] = false;
- }
- else {
- boolean a = memo[i-1][j];
- boolean b = memo[i-1][j-arrs[i]];
- memo[i][j] = a|| b;
- }
- }
- }
- return memo[arrs.length-1][k];
- }
-
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。