unique-pathsV2.dart (1311B)
1 //This is a working implementation of the traveler problem 2 //also known as unique paths on leetcode. Basically find all paths 3 //from the top left to the bottom right of the board. 4 //My solution uses memoization to remember how many paths a given 5 //shape (m*n) rectangle has from top left to bottom right and then returning that to the previous iteration. 6 //I also had to use string concatenation as keys because lists can't be used 7 //as keys in dart because it is a pointer to the list not the values themselves. (Headache) 8 //The time complexity of this code is O(m*n). 9 //Time: 251ms Beats: 70.79% 10 //Memory: 144.4MB Beats: 23.53% 11 12 class Solution { 13 Map<String , int> blocks_solved = {}; 14 int paths = 0; 15 int uniquePaths(int m, int n) { 16 String m_str = m.toString(); 17 String n_str = n.toString(); 18 if(blocks_solved[m_str + " " + n_str] != null){ 19 return (blocks_solved[m_str + " " + n_str] ?? 0); 20 } 21 if(blocks_solved[n_str + " " + m_str] != null){ 22 return (blocks_solved[n_str + " " + m_str] ?? 0); 23 } 24 int block_val = 0; 25 if(m == 1 || n == 1){ 26 return 1; 27 } 28 if(m > 1){ 29 block_val += uniquePaths(m - 1, n); 30 } 31 if(n > 1){ 32 block_val += uniquePaths(m , n - 1); 33 } 34 blocks_solved[m_str + " " + n_str] = block_val; 35 return block_val; 36 } 37 }