java 具有递归的迭代解决方案

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 具有递归的迭代解决方案相关的知识,希望对你有一定的参考价值。

import java.io.*;
import java.util.*;

class Solution {
  public static void main(String[] args) {
    Solution solution = new Solution();
    int[] input = {3,4,5};  
    
    solution.print(input);
    System.out.println();
    solution.printR(input);
    System.out.println();
    
    
    System.out.println("ABA, Result: " + solution.isPalindrome("ABA"));
    System.out.println("ABBA, Result: " + solution.isPalindrome("ABBA"));
    System.out.println("ABCABA, Result: " + solution.isPalindrome("ABCABA"));

    System.out.println("ABA, Result: " + solution.isPalindromeR("ABA"));
    System.out.println("ABBA, Result: " + solution.isPalindromeR("ABBA"));
    System.out.println("ABCABA, Result: " + solution.isPalindromeR("ABCABA"));

    
    System.out.println("2pow2 Result: " + solution.aRaiseB(2,2));
    System.out.println("3pow3, Result: " + solution.aRaiseB(3,3));
    System.out.println("5pow4, Result: " + solution.aRaiseB(5,4));
    
    System.out.println("2pow2 Result: " + solution.aRaiseBR(2,2));
    System.out.println("3pow3, Result: " + solution.aRaiseBR(3,3));
    System.out.println("5pow4, Result: " + solution.aRaiseBR(5,4));
  }
  
  public void print(int[] input) {
   for(int i=0;i<input.length;i++){
    System.out.print(input[i] + " "); 
   }
  }
  
  public void printR(int[] input){
    if(input.length < 1) {
      return;
    }
    System.out.print(input[0] + " ");
    printR(Arrays.copyOfRange(input,1,input.length));
  }
  
  public boolean isPalindrome(String input) {
    if(input.length() < 2) {
      return true; 
    }
    int start = 0;
    int end = input.length()-1;
    while(start < end) {
      if(input.charAt(start++) != input.charAt(end--)) {
        return false;
      }
    }
    return true;
  }
  
  public boolean isPalindromeR(String input) {
    if(input.length() < 2) {
      return true;
    }
    return input.charAt(0) == input.charAt(input.length()-1) && 
          isPalindromeR(input.substring(1,input.length()-2));
  }
  
  public int aRaiseB(int a, int b) {
    if(a==0) return 0;
    
    int result = 1;
    for(int i=0; i < b;i++) {
      result *=a;
    }
    
    return result;
  }
  
  public int aRaiseBR(int a, int b) {
    if(a==0) return 0;
    if(b==0) return 1;
    return a * aRaiseBR(a,b-1);
  }
}

以上是关于java 具有递归的迭代解决方案的主要内容,如果未能解决你的问题,请参考以下文章

使用迭代方法解决递归

Python 是不是具有用于一阶递归关系的迭代递归生成器函数?

递归:如何避免 Python set changed set 在迭代 RuntimeError 期间

Python用迭代(yield)和递归解决八皇后问题

Leetcode24. 两两交换链表中的节点(JAVA迭代+递归)

函数进阶之迭代器,递归