leetcode

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

combinations.dart (1295B)


      1 //Given an input where n is the number of values and 
      2 //k is the length of each combination return all possible combinations.
      3 //My solution iterates through the list and returns
      4 //each possible combination each time it iterates the first
      5 //index of the list moves one to the right as to not return both
      6 //1,2 and 2,1 which would happen if you returned all permutations
      7 //of the second index.
      8 //Time: 279ms Beats: 83.33%
      9 //Memory: 155.6MB Beats: 30.56%
     10 
     11 class Solution {
     12   List<List<int>> combine(int n, int k) {
     13       List<int> values = [];
     14       for(int i = 1 ; i < n + 1; ++i){
     15           values.add(i);
     16       }
     17       return allCombinations(k, values, []);
     18   }
     19   List<List<int>> allCombinations(int length , List<int> options, List<int> current){
     20       if(length == current.length){
     21           return [current];
     22       }
     23       List<List<int>> return_list = [];
     24       for(int i = 0; i <  options.length ; ++i){
     25           List<int> new_curr = List.from(current);
     26           List<int> opts = List.from(options);
     27           opts = opts.sublist(i + 1);
     28           new_curr.add(options[i]);
     29           List<List<int>> ret = allCombinations(length , opts, new_curr);
     30           for(int i = 0 ; i < ret.length ; ++i){
     31               return_list.add(ret[i]);
     32           }
     33       }
     34       return return_list;
     35   }
     36 }