【问题标题】:Compute sets of size n given an array给定一个数组,计算大小为 n 的集合
【发布时间】:2021-02-11 10:29:41
【问题描述】:

我不确定我的问题标题是否有意义,或者即使我完全知道我想要了解什么,但假设你在数组中得到了一些字母和一个数字 n:

char[] arr = ['a','b'], n = 4

How can you compute all the permutations of size n?

aaaa
bbbb
abab
bbaa
aabb
... (and so on)

我不知道该怎么做,非常感谢一些帮助。我想我为什么感到困惑是因为您想要制作的大小 (4) 大于数组中元素的数量,而我以前从未见过。

【问题讨论】:

  • 排列计数 = array.length^n。对于您的示例,它是 2^4=16

标签: java arrays recursion permutation


【解决方案1】:

您的问题的一个解决方案可能是创建一个递归方法,该方法使集合中的所有排列(在本例中为 a 和 b)并调用它 n 次以形成一个字符串。

【讨论】:

    【解决方案2】:

    在伪代码中...

    接受字符串参数的递归函数:

    • 如果长度为4,则将字符串添加到结果中
    • 否则,循环字符:
      • 使用 param + char 递归调用函数

    首先调用一个空白的函数。

    【讨论】:

      【解决方案3】:

      尝试以不同的方式查看问题,假设给您n 框,在每个框中您需要放置从数组arr 中选择的一个字母,因为数组中的每个字母都可以多次使用,因此对于每个框,您有与 arr.length 一样多的选择,将所有框组合在一起,您将拥有总共 arr.length ^ n 排列,这是使用递归的 java 中一个简单的工作示例:

      public class Test {
      
          static List<String> res;
      
          public static void main(String[] args){
      
              char[] arr = {'a','b'};
              int n = 4;
      
              res = new ArrayList<>();
              permutate(arr, new char[n], n, 0);
      
              System.out.println("size = " + res.size());
              System.out.println("permutations = " + Arrays.toString(res.toArray()));
          }
      
          static void permutate(char[] arr, char[] permutation, int n ,int idx){
              if(idx == n){
                  res.add(new String(permutation));
                  return;
              }
      
              for(int i = 0; i < arr.length; i++){
                  permutation[idx] = arr[i];
                  permutate(arr, permutation, n, idx + 1);
              }
          }
      
      }
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-27
        • 1970-01-01
        相关资源
        最近更新 更多