Skip to content

Instantly share code, notes, and snippets.

@imsardine
Created January 7, 2015 03:44
Show Gist options
  • Save imsardine/bc190b1a373463695131 to your computer and use it in GitHub Desktop.
Save imsardine/bc190b1a373463695131 to your computer and use it in GitHub Desktop.
[程式題] 有一個樓梯,你每次只能爬 1 階、3 階,或 5 階。請寫一個 function,傳入樓梯總長為 N 階,回傳總共有多少種走法。 例如:樓梯總長為 5 階,走法有「1、1、1、1、1」、「5」、「1、3、1」、「1、1、3」、「3、1、1」,共 5 種 (注意:要剛好走完、不得超過總長,且不能後退)
import sys
def main(steps):
print "# of combination(s): %s" % climb(int(steps))
def climb(steps, paces=[1, 3, 5]):
if steps <= 0: return 1
return sum([climb(steps - pace, paces) for pace in paces if pace <= steps])
if __name__ == '__main__':
if len(sys.argv) == 1:
print 'Usage: %s STEPS' % sys.argv[0]
sys.exit(-1)
main(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment