首页 > 其他 > 详细

Epic - Desirable Number

时间:2015-06-14 12:15:20      阅读:201      评论:0      收藏:0      [点我收藏+]

A number is called ‘desirable‘ if all thedigits are strictly ascending eg: 159 as 1<5<9. You know that your rivalhas a strictly numeric password that is ‘desirable‘. Your close ally has givenyou the number of digits (N) in your rival‘s password. WAP th\hjtat takes in‘N‘ as input and prints out all possible ‘desirable‘ numbers that can be formedwith N digits.

递归:参数记录剩余需要生成的长度和最小的能append的数字

def bfs(remain,start,string)
  if remain == 0
    @ans << string
  else
    (start..9).each { |i| bfs(remain-1, i+1, string + i.to_s)}
  end
end

def desire_number(n)
  @ans = []
  bfs(n,1,‘‘)
  @ans
end

循环:用两个数组分别保存i-1的情况和i的情况 i from 1 to n

def desire_number(n)
 return 0 if n == 0 a
= [1] (n-1).times do b = [] a.each {|x| (x[-1].to_i..9).each{|y| b << x+y.to_s}} a = b end a end

Epic - Desirable Number

原文:http://www.cnblogs.com/lilixu/p/4574828.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!