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
  • 相关阅读:
    链表中倒数第K个结点
    关于栈的经典问题---判断一个栈的出栈序列是不是有效的
    剑指Offer-用两个栈实现队列
    Netty与NIO
    牛客-反转数字
    N叉树的最大深度-DFS
    version can neither be null, empty nor blank
    剑指 Offer 16. 数值的整数次方
    Vue基础语法与指令
    ES6常用语法
  • 原文地址:https://www.cnblogs.com/dalas/p/3107670.html
Copyright © 2011-2022 走看看