leetcode

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

combination-sum-iii.dart (1837B)


      1 //Given a number k where k is the number of values to add together
      2 //and n is the target value return all combinations of numbers 1-9
      3 //that add up to n where no numbers 1-9 are used twice in the same
      4 //list, and no duplicate lists are returned. 
      5 //To do this I first created all of the options (1-9). I then
      6 //called a function that takes the number of values needed, the target number,
      7 //and the remaining options. For each iteration it tries to see if all options
      8 //create viable answers if they do that means that the length of the list
      9 //is k and the target = 0. Then the list is returned to the parent which adds on the value
     10 //that is recursed with moving up until reaching the top.
     11 
     12 //Note: In order to not return duplicate results I made
     13 //sure to use a sublist starting from the checked value that
     14 //way you will not remove just a single value and thus try 1 , 3 and 3 , 1 which would
     15 //return permutations not combinations.
     16 
     17 //Time: 263ms Beats: 100%
     18 //Memory: 141.6MB Beats: 100%
     19 class Solution {
     20   List<List<int>> combinationSum3(int k, int n) {
     21       List<int> opts = [];
     22       for(int i = 1 ; i <= 9 ; ++i){
     23           opts.add(i);
     24       }
     25       return combinations(opts, n , k);
     26   }
     27   List<List<int>> combinations(List<int> options , int target, int nums){
     28       if(nums == 0){
     29           if(target == 0){
     30               return [[]];
     31           }
     32           return [];
     33       }
     34       List<List<int>> return_list = [];
     35       for(int i = 0 ; i < options.length ; ++i){
     36           List<int> opts_new = options.sublist(i + 1);
     37           List<List<int>> combos = combinations(opts_new , target - options[i] , nums - 1);
     38           for(int x = 0 ; x < combos.length ; ++x){
     39               return_list.add(combos[x]);
     40               return_list[return_list.length - 1].add(options[i]);
     41           }
     42       }
     43       return return_list;
     44   }
     45 }