377. Combination Sum IV

377. Combination Sum IV

  • 題目描述:Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.

  • Example:

    nums = [1, 2, 3]
    target = 4
    
    The possible combination ways are:
    (1, 1, 1, 1)
    (1, 1, 2)
    (1, 2, 1)
    (1, 3)
    (2, 1, 1)
    (2, 2)
    (3, 1)
    
    Note that different sequences are counted as different combinations.
    
    Therefore the output is 7.
  • 題目大意:給定一個數組,一個target,問數組中有多少組合,使它們的和爲目標數target

  • 代碼

    package DP;
    
    import java.util.Arrays;
    
    /**
    * @author OovEver
    * 2018/1/3 16:11
    */
    public class LeetCode377 {
      public static int combinationSum4(int[] nums, int target) {
          Arrays.sort(nums);
    //        dp[i]表示,以i爲target有多少種組成情況
          int[] dp = new int[target + 1];
          for(int i=1;i<target+1;i++) {
              for (int num : nums) {
                  if (i < num) {
                      break;
                  }
                  if (i == num) {
                      dp[i] += 1;
                  } else {
                      dp[i] += dp[i - num];
                  }
              }
          }
          return dp[target];
      }
    }
    
發佈了207 篇原創文章 · 獲贊 69 · 訪問量 39萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章