Created
March 14, 2020 13:38
-
-
Save junminstorage/b996ad04a9daff03127ffd719411e9f3 to your computer and use it in GitHub Desktop.
given a number, we can either reduce it by 1 or divided by 2 or 3, find the minimum step to reach 1 from any given number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static Map<Integer, Integer> store = new HashMap<>(); | |
static public int dfs(int current) { | |
if(current == 1) | |
return 0; | |
if(store.containsKey(current)) | |
return store.get(current); | |
int min = dfs(current-1) + 1; | |
if(current%2==0) | |
min = Math.min(min, dfs(current/2) + 1); | |
if(current%3==0) | |
min = Math.min(min, dfs(current/3) + 1); | |
store.put(current, min); | |
return min; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment