zoukankan      html  css  js  c++  java
  • Backpack VI

    Given an integer array nums with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target

    Example

    Given nums = [1, 2, 4], target = 4

    The possible combination ways are:
    [1, 1, 1, 1]
    [1, 1, 2]
    [1, 2, 1]
    [2, 1, 1]
    [2, 2]
    [4]
    

    return 6

    一开始用backtracking 发现总是超时,后来网上找到的DP解法 简单有效。。类似于找钱(coin change)的问题

     1 public class Solution {
     2     /**
     3      * @param nums an integer array and all positive numbers, no duplicates
     4      * @param target an integer
     5      * @return an integer
     6      */
     7     public int backPackVI(int[] nums, int target) {
     8         // Write your code here
     9         int[] count = new int[target+1];
    10         count[0] = 1;
    11         
    12         for(int i=1;i<=target;i++){
    13             for(int j=0;j<nums.length;j++){
    14                 if(i-nums[j]>=0){
    15                     count[i]+=count[i-nums[j]];
    16                 }
    17             }
    18         }
    19         return count[target];
    20     }
    21 }
  • 相关阅读:
    [POI2000]病毒
    枪战(maf)
    禅与园林艺术(garden)
    The Cave
    集合选数
    BZOJ3990 排序(sort)
    区间(interval)
    太空飞船(spaceship)
    数表( table )
    Printed Circuit Board (board)
  • 原文地址:https://www.cnblogs.com/xinqiwm2010/p/6836056.html
Copyright © 2011-2022 走看看