庞果网在线编程子序列的个数问题ruby解答

来源:互联网 发布:全景展示系统源码 编辑:程序博客网 时间:2024/04/30 01:34

题目地址: http://hero.pongo.cn/Question/Details?ID=111&ExamID=109

题目详情

本题同样来自caopengcs,只要你有兴趣,每个人都可以出题(出题入口在主页右侧边栏“贡献题目”->“我要发布”内),以下是题目详情:

子序列的定义:对于一个序列a=a[1],a[2],......a[n],则非空序列a'=a[p1],a[p2]......a[pm]为a的一个子序列,其中1<=p1<p2<.....<pm<=n。

例如:4,14,2,3和14,1,2,3都为4,13,14,1,2,3的子序列。

对于给出序列a,有些子序列可能是相同的,这里只算做1个,要求输出a的不同子序列的数量。



输入: 长度为n的数组1<=n<=100,数组元素0<=a[i]<=110

输出:子序列 的个数对1000000007取余数的结果(由于答案比较大,输出Mod 1000000007的结果即可)。


这个题目前一阵子就看过了,很长时间都没有思路。 想到 应该如何递归呢。首先想到的是按照人的计算思路来计算。

总个数 = 大小为1的自序列的个数 + 大小为2 的子序列的个数 + …… + 大小为n的子序列个数


这种思路也不是不可行,只是太过于浪费内存了, 对计算机来说应该有更好的思路吧。

后来网络搜索了一下,才找到正确的思路。思路见链接:http://www.cnblogs.com/bestDavid/p/subsequence.html


class Sequence  def initialize(array)    @array = array  end  def sub_sequence_count    return 0 if @array.empty?    return 1 if @array.count == 1    equal_last_position = @array[0..-2].rindex(@array.last)    if equal_last_position == nil      2 * Sequence.new(@array[0..-2]).sub_sequence_count + 1    else      2 * Sequence.new(@array[0..-2]).sub_sequence_count - Sequence.new(@array[0...equal_last_position]).sub_sequence_count    end  endenddescribe Sequence do   it "should be 1 if sequence is 1" do     Sequence.new([1]).sub_sequence_count.should == 1   end   it "should be 3 if sequence is [1, 2]" do     Sequence.new([1, 2]).sub_sequence_count.should == 3   end   it "should be 5 if sequence is [1, 1, 2]" do     Sequence.new([1, 1, 2]).sub_sequence_count.should == 5   end   it "should be 6 if sequence is [1, 2, 1]" do     Sequence.new([1, 2, 1]).sub_sequence_count.should == 6   end   it "should be 11 if sequence is [1, 2, 1, 2]" do     Sequence.new([1, 2, 1, 2]).sub_sequence_count.should == 11   endend


原创粉丝点击