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

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
end
end

describe 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
end
end

• 本文已收录于以下专栏：

举报原因： 您举报文章：庞果网在线编程子序列的个数问题ruby解答 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)