zoukankan      html  css  js  c++  java
  • 算法复习2(全排序,从M取N个数) *不考虑重复数据

    全排序

     1  static void AllSort(int[] arr, string rtnStr)
     2         {
     3             if (arr.Length == 0)
     4             {
     5                 Console.WriteLine(rtnStr);
     6                 return;
     7             }
     8 
     9             int i = -1;
    10             string temp = rtnStr;
    11 
    12             while ((++i) < arr.Length)
    13             {
    14                 rtnStr = rtnStr + arr[i] + " ";
    15 
    16                 int[] rtnArray = GetNextArray(arr, i);
    17                 AllSort(rtnArray, rtnStr);
    18 
    19                 rtnStr = temp;
    20             }
    21         }
    22 
    23         static int[] GetNextArray(int[] arr, int index)
    24         {
    25             int[] rtnArray = arr.Where(p => p != arr[index]).ToArray();
    26 
    27             return rtnArray;
    28         }
    View Code

    从M个数取N个数

     1  static void FetchNumN(int[] arr, string rtnStr, int depth, int num)
     2         {
     3             if (depth == num)
     4             {
     5                 Console.WriteLine(rtnStr);
     6                 return;
     7             }
     8 
     9             int i = -1;
    10             string tempStr = rtnStr;
    11             int tempDepth = depth;
    12 
    13             while ((++i) < arr.Length)
    14             {
    15                 rtnStr = rtnStr + arr[i] + " ";
    16                 depth++;
    17 
    18 
    19                 int[] rtnArray = GetNextFetchArray(arr, i);
    20                 FetchNumN(rtnArray, rtnStr, depth, num);
    21 
    22                 rtnStr = tempStr;
    23                 depth = tempDepth;
    24             }
    25         }
    26 
    27         static int[] GetNextFetchArray(int[] arr, int index)
    28         {
    29             int[] rtnArray = new int[arr.Length - index - 1];
    30             int j = -1;
    31             for (int i = index + 1; i < arr.Length; i++)
    32             {
    33                 rtnArray[++j] = arr[i];
    34             }
    35 
    36             return rtnArray;
    37         }
    View Code

    调用方式

    1  int[] array = new int[] { 1, 2, 3, 4, 5 };
    2             AllSort(array, "");
    3             FetchNumN(array, "", 0, 3);
    View Code
  • 相关阅读:
    LF 第三章 装饰器和迭代器相关
    Python 文件管理
    Python 强制类型转换
    安装模块
    LF 第三章
    pep8 Python编码规则
    Help on module pyclbr:
    Help on class timedelta in module datetime:
    Help on function meshgrid in module numpy.lib.function_base:
    Help on module matplotlib.cm in matplotlib:
  • 原文地址:https://www.cnblogs.com/dalas/p/3107670.html
Copyright © 2011-2022 走看看