确定集合中是否存在两个其和刚好为X的元素?

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cocreatefuture/article/details/70301463

《算法导论》第三版 P22,2.3-7练习题

list1 = [1,2,3,4,5,6,7,8,10,19];
count = len(list1);
stack4 = []
stack2 = []

def bsf2(list0, start1, end1, start2, end2, a):        
    flags = [False, False, False, False];

    if len(stack4) > 0:
        return True

    if start1 == end1 and start2 == end2:
        if a == list0[start1] + list0[end2]:
            stack4.append(end2)
            stack4.append(end2)
            stack4.append(start1)
            stack4.append(start1)
            return True
        return False

    if list0[start1] + list0[start2] > a or list0[end1] + list0[end2] < a:
        return False

    mid1 = (int)((start1 + end1) /2);
    mid2 = (int)((start2 + end2) /2);
    flags[0] = bsf2(list0, start1, mid1, start2, mid2, a);
    flags[1] = bsf2(list0, start1, mid1, mid2 + 1, end2, a);
    flags[2] = bsf2(list0, mid1 + 1, end1, start2, mid2, a);
    flags[3] = bsf2(list0, mid1 + 1, end1, mid2 + 1, end2, a);

    if flags[0] and flags[1] and flags[2] and flags[3]:
        stack4.append(end2)
        stack4.append(start2)
        stack4.append(end1)
        stack4.append(start1)
        return True

    if flags[0] and flags[1] and flags[2]:
        return bsf2(list0, start1, end1, start2, mid2, a)

    if flags[0] and flags[1] and flags[3]:
        return bsf2(list0, start1, end1, mid2 + 1, end2, a)

    if flags[0] and flags[2] and flags[3]:
        return bsf2(list0, start1, mid1, start2, end2, a)

    if flags[1] and flags[2] and flags[3]:
        return bsf2(list0, mid1 + 1, end1, start2, end2, a)

    if flags[0] and flags[2]:
        return bsf2(list0, start1, mid1, start2, mid2, a)

    if flags[0] and flags[3]:
        return bsf2(list0, start1, mid1, mid2 + 1, end2, a)

    if flags[1] and flags[2]:
        return bsf2(list0, mid1 + 1, end1, start2, mid2, a)

    if flags[1] and flags[3]:
        return bsf2(list0, mid1 + 1, end1, mid2 + 1, end2, a)


def rbsf(list0, start, end, a):
    if start == end:
        return
    if list0[start] + list0[start + 1] > a or list0[end] + list0[end - 1] < a:
        return
    stack2.append(end);
    stack2.append(start);

    mid = (int)((start + end) / 2);
    rbsf(list0, start, mid, a);
    rbsf(list0, mid + 1, end, a);

    return;

rbsf(list1, 0, count - 1, 9);
stack2.reverse();
if len(stack2) > 0:
    print(stack2);
else:
    print("find no section")

while(len(stack2) > 0):
    print(stack2[0:2])
    start = stack2.pop(0)
    end = stack2.pop(0)
    mid = (int)((start + end) / 2);
    flag = bsf2(list1, start, mid, mid + 1, end, 9)
    if flag:
        print(stack4)
        break
    else:
        print("Not found")

算法中,主要使用了递归算法。一个递归算法确定两个加数存在于集合的哪段区域,另一个递归算法确定两个加数分别存在于两个分区的哪个子分区内。

该程序可以找出所有可能存在的加数组合,但是我在找到一个加数组合时就跳出了。

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页