zoukankan      html  css  js  c++  java
  • 算法题

    1. “一副从1到n的牌,每次从牌堆顶取一张放桌子上,再取一张放牌堆底,
    2.  直到手里没牌,最后桌子上的牌是从第一张到最后一张的排列,梳理牌的排列顺序的算法。”
      例如:
      原数据:1 2 3 4 5
      第一次:3 4 5 2   1
      第二次:5 2 4     3
      第三次:4 2       5
      第四次:2         4

      递归实现
      import java.util.ArrayList;
      import java.util.List;
      
      public class Test {
      
          public static void main(String[] args) {
      
              int n = 5;
              List<Integer> sourceList = new ArrayList<>(16);
              List<Integer> destList = new ArrayList<>(16);
              for (int i = 1; i <= n; i++) {
                  sourceList.add(i);
              }
              output(sourceList, destList);
      
              for (Integer num : destList) {
                  System.out.println(num);
              }
          }
      
          /**
           * 递归
           *
           * @param sourceList
           * @param destList
           */
          public static void output(List<Integer> sourceList, List<Integer> destList) {
              //1.将第一个数加入到目标list,将原list 第一个数去除
              //2.将新list第1个数去除,并加入到新list末尾
              //3.递归
      
              if (sourceList.isEmpty()){
                  return;
              }
              for ( int i = 0; i < 2 ;i++){
                  if (0==i){
                      destList.add(sourceList.get(0));
                      sourceList.remove(0);
                  }else {
                      if (!sourceList.isEmpty()){
                          int temp = sourceList.get(0);
                          sourceList.remove(0);
                          sourceList.add(temp);
                      }
                  }
              }
              output(sourceList,destList);
          }
      }
      

        

        

  • 相关阅读:
    16. 3Sum Closest
    17. Letter Combinations of a Phone Number
    20. Valid Parentheses
    77. Combinations
    80. Remove Duplicates from Sorted Array II
    82. Remove Duplicates from Sorted List II
    88. Merge Sorted Array
    257. Binary Tree Paths
    225. Implement Stack using Queues
    113. Path Sum II
  • 原文地址:https://www.cnblogs.com/Andrew520/p/10886643.html
Copyright © 2011-2022 走看看