【问题标题】:Algorithm to find a sequence of sub-sequences查找子序列序列的算法
【发布时间】:2013-03-26 15:46:36
【问题描述】:

序列 [1,2,3] 考虑。这个序列有以下6种不同的序列:[1]and [2]and [3] and [1,2] and [2,3] and [1,2,3]

注意!初始序列的长度最多可达 100 位。 请帮我。如何制作以下序列? 我喜欢更多地研究这种算法。请告诉我这类算法的名称。

【问题讨论】:

  • 100位数字,有5050个子序列。你真的想要所有这些吗?
  • 所以,现在嵌套循环打印序列有一个花哨的名字算法
  • @JanDvorak [1,3] 子序列不包含在此算法中。所以 100 个数字有 200 个子序列!
  • @KasiyA 确实如此。那将是 2^1024 个子序列,比 5050 大得多,几乎不适合这个评论字段(不是框本身),很难手动转录,绝对不值得阅读。
  • @JanDvorak 和 [1,2,3,4,5,6] 我们有这个子 [1] [2] [3] [4] [5] [6] [1,2] [2,3] [3,4] [4,5] [5,6] [1,2,3,4,5,6]。 n*2 个子序列。

标签: algorithm sequence


【解决方案1】:

这是一个打印所有子序列的 c 代码。算法使用嵌套循环。

    #include<stdio.h>

  void seq_print(int A[],int n)
{
    int k;
    for(int i =0;i<=n-1;i++)
    {
        for(int j=0;j<=i;j++)
        {
            k=j;
            while(k<=i)
            {
                printf("%d",A[k]);
                k++;

            }
            printf("\n");
        }
}

}

void main()
{
    int A[]={1,2,3,4,5,6,7,8,9,0};
    int n=10;
    seq_print(A,n);

}

【讨论】:

    【解决方案2】:

    您的问题可以简化为Combination 问题。 stackoverflow 中已经有很多解决方案。您可以查看this,它可能对您有用。

    【讨论】:

      【解决方案3】:

      它被称为a power set(在你的情况下,空集被排除在外)。

      要构建一个幂集,从一个包含空集的集合开始;然后 对于输入集中的每个项目,扩展幂集及其迄今为止累积的所有子集 包含当前项目(在 Python 中):

      def powerset(lst):
          S = [[]]
          for item in lst:
              S += [subset + [item] for subset in S]
          return S
      

      例子:

      print(powerset([1, 2, 3]))
      # -> [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
      

      为避免一次生成所有子集,可以使用递归定义:

      • 空集的幂集是其中包含空集的集合
      • 具有n 项的集合的幂集包含幂集的所有子集 包含n - 1 项的集合以及包含n-th 项的所有这些子集。
      def ipowerset(lst):
          if not lst: # empty list
              yield []
          else:
              item, *rest = lst
              for subset in ipowerset(rest):
                  yield subset
                  yield [item] + subset
      

      例子:

      print(list(ipowerset([1, 2, 3])))
      # -> [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
      

      另一种生成幂集的方法是为所有 r 从零到输入集的大小 (itertools recipe) 生成 r-length 子序列(组合):

      from itertools import chain, combinations
      
      def powerset_comb(iterable):
          s = list(iterable)
          return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
      

      例子:

      print(list(powerset_comb([1, 2, 3])))
      # -> [(), (1,), (2,), (3,), (1,2), (1,3), (2,3), (1,2,3)]
      

      另见what's a good way to combinate through a set?

      【讨论】:

      • 请注意,[1,3] 不是示例输出的一部分。问题不清楚,我推测它是子数组,添加了一个答案,后来当我没有得到 OP 的回复时将其删除。也许你的答案就是他们想要的,而 [1,3] 只是一个遗漏。
      • @Knoothe:你是对的。 OP 可能会询问subarrays,如your answer,而不是一般的子序列。
      • [1,3] 不包括有问题的输出。问题说 [1,2.3] 有 6 个子,但你有 7 个子
      猜你喜欢
      • 2014-06-27
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多