Skip to content

Instantly share code, notes, and snippets.

@johnrichardrinehart
Last active September 15, 2020 22:15
Show Gist options
  • Save johnrichardrinehart/b1228d7dc2a8305a514c46283aedc616 to your computer and use it in GitHub Desktop.
Save johnrichardrinehart/b1228d7dc2a8305a514c46283aedc616 to your computer and use it in GitHub Desktop.
// This code is an attempt to solve (probslem description below) https://leetcode.com/explore/challenge/card/september-leetcoding-challenge/555/week-2-september-8th-september-14th/3459/
// A more efficient solution can be devised using dynamic programming: https://www.geeksforgeeks.org/count-ways-reach-nth-stair/
// ----- START Problem Description -----
// You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
// Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
// Example 1:
// Input: nums = [1,2,3,1]
// Output: 4
// Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
// Total amount you can rob = 1 + 3 = 4.
// Example 2:
// Input: nums = [2,7,9,3,1]
// Output: 12
// Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
// Total amount you can rob = 2 + 9 + 1 = 12.
// Constraints:
// 0 <= nums.length <= 100
// 0 <= nums[i] <= 400
// ----- END Problem Description -----
// Note: This revision uses memoization, however the call stack still grows too much
package main
import "log"
func main() {
log.Println(genpath(8))
}
// returns an iterator of skip slices to be used as index offsets
func genpath(n int) [][]int {
var rec func(i, n int) [][]int
memo := make(map[int][][]int)
rec = func(idx, n int) [][]int {
var res [][]int
if n < 1 {
return nil
}
if n == 1 || n == 2 {
return [][]int{[]int{idx}}
}
if n == 3 {
return [][]int{[]int{0 + idx, 2 + idx}}
}
if n == 4 {
return [][]int{[]int{0 + idx, 2 + idx}, []int{0 + idx, 3 + idx}}
}
if _, ok := memo[n]; !ok {
jump2 := rec(idx+2, n-2)
for _, path := range jump2 {
res = append(res, append([]int{idx}, path...))
}
jump3 := rec(idx+3, n-3)
for _, path := range jump3 {
res = append(res, append([]int{idx}, path...))
}
memo[n] = res
}
return memo[n]
}
defer func() {
log.Println(n, memo[5])
}()
return append(rec(0, n), rec(1, n-1)...)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment