leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

combination-sum-iv.dart (1504B)


      1 //Given a list of options (nums) where each value is unique
      2 //and each value can be used as many times as you would like return
      3 //the number of permutations that can add up to the target value.
      4 
      5 //To solve this I used DP and memoization. The first thing
      6 //to understand is since the nums list will not change as you 
      7 //recurse you can use a simple memoization technique because you 
      8 //do not have changing constraints depending on which numbers
      9 //have been used in the past. Given this each time you run into
     10 //a target value you can check how many ways that target can become 0
     11 //if the problem has been done before return the answer if not recurse to find
     12 //all possible ways to reach 0 from that position with the options in the nums list.
     13 //Then return the possible ways to do it to the parent. Continue doing this until all 
     14 //nums have been iterated through and return the final number of satisfying permutations.
     15 
     16 //Time: 282ms Beats: 100%
     17 //Memory: 141.7MB Beats: 100%
     18 
     19 class Solution {
     20   Map<int,int> memo = {};
     21   int combinationSum4(List<int> nums, int target) {
     22       if(memo[target] != null){
     23           return (memo[target] ?? 0);
     24       }
     25       if(target <= 0){
     26         if(target == 0){
     27             return 1;
     28         }
     29         if(target < 0){
     30             return 0;
     31         }
     32       }
     33       int return_val = 0;
     34       for(int i = 0 ; i < nums.length ; ++i){
     35           return_val += combinationSum4(nums, target - nums[i]);
     36       }
     37       memo[target] = return_val;
     38       return return_val;
     39   }
     40 }