选择和未选择的子序列相同

问题描述 投票:-2回答:1

我们有2N整数的序列。我们需要确定是否可以选择N整数的子序列,这样选择的序列和未选择的序列将是相同的。例如,它可能是1 2 1 2 3 3,但1 2 3 3 1 2是不可能的。

任何想法如何解决?

algorithm
1个回答
0
投票

由于您没有提供任何代码或语言来解决这个问题,我能做的最好的就是给你一个伪代码:

这个想法是有两个堆栈将被填充,无论你是否已经在下面发布的方法中的一个或另一个中添加了一个数字:

if (stack1 has N) {
    add N to stack2
} else {
    add N to stack1
}

然后从每个堆栈中取出每个数字

function/method isItPossible(arrayWithSequence) {
    //Here add the numbers in the stacks

    while (both stacks are not empty) {
        if (lastNumberInStack1 is different from lastNumberInStack2) {
            return false
        }
    }
    return true
}

然后打电话

print(isItPossible(yourSequenceHere));

这应该打印truefalse根据是否可能。

© www.soinside.com 2019 - 2024. All rights reserved.