• 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 }
  • 相关阅读:
    第五周活动进度表
    第四周学习进度条
    软件工程概论作业3
    第三周活动进度
    小学生运算程序2
    课堂作业1
    jsp登陆界面代码
    《构建之法》读书笔记04
    《构建之法》读书笔记03
    《构建之法》读书笔记02
  • 原文地址:https://www.cnblogs.com/xinqiwm2010/p/6836056.html
Copyright © 2020-2023  润新知