0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

LeetCode日本語修行11日目- [377-コンビネーションサムIV]

Last updated at Posted at 2021-04-24

Combination Sum IV

参考:https://leetcode.com/problems/combination-sum-iv/
###問題の内容:
相異なる整数配列nums,指定整数targetが与えられた場合、targetに加算される可能な組み合わせの数を返します。
###例:
例1:
Input: nums = [1,2,3], target = 4
Output: 7
Explanation:
7の組み合わせ:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)

例2:
Input: nums = [9], target = 3
Output: 0
###ヒント:
1 <= nums.length <= 200
1 <= nums[i] <= 1000
All the elements of nums are unique.
1 <= target <= 1000


このような問題を見た瞬間、最初に出た単語はDP...
先ず問題を分割します。
target=0の場合
何も選択しないのは正し、これしかない、
dp[0]=1
1 < x <=targetの場合
dp[x] != 0,dp[x]の中の組合の最後のnum必ずnumsの中に入ります。
そして、今targetTemp = target - num
これを貰った結果はdp[target-num]
dp[target-num]の中に、全ての結果をnumを入れると、全ての加算結果はtargetです。
num<targetの時
全てのdp[target-num]の結果を加算してのはdp[target]です

class Solution {
    fun combinationSum4(nums: IntArray, target: Int): Int {

       var dpArray = IntArray(target+1)
        dpArray[0] = 1
        for(i in 1 .. target){
            for(num in nums){
                if(num <= i){
                    dpArray[i] += dpArray[i - num]
                }
            }
        }
        return dpArray[target]
    }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?