Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save junminstorage/b996ad04a9daff03127ffd719411e9f3 to your computer and use it in GitHub Desktop.
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
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