如何递归添加功能

时间:2018-08-08 16:27:35

标签: java algorithm

我对如何用JAVA编写代码感到困惑:存在一个有N步的楼梯,您一次可以爬1步或2步。给定N,编写一个函数,该函数返回您爬楼梯的独特方式的数量。步骤的顺序很重要。

例如,如果N为4,则有5种独特的方式:

1, 1, 1, 1
2, 1, 1
1, 2, 1
1, 1, 2
2, 2

如果您不能一次爬升1或2步,而是可以从一组正整数X爬升任何数字怎么办?例如,如果X = {1、3、5},则您一次可以爬1、3或5步。

基本上,我可以做第一部分,并用更复杂的部分来理解逻辑,答案是:f(n)= f(n-1)+ f(n-3)+ f(n-5 )。谁能帮我?这是我的方法:

public static void main(String[] args) {
 int n = 4;
 Set < Integer > list = new HashSet < Integer > ();
 list.add(1);
 list.add(3);
 list.add(5);
 int ways = reachNFloorSet(list, n, 0);
 //     int ways = reachNFloor(n);
 System.out.println(n + " Floor is reached in " + ways + " different way/s.");
}


public static int reachNFloor(int n) { // easy part
 if (n <= 1) {
  return 1;
 }
 return reachNFloor(n - 1) + reachNFloor(n - 2);
}

public static int reachNFloorSet(Set < Integer > numbers, int n, int sum) {
 if (n < 0) {
  return 0;
 } else if (n == 0) {
  return 1;
 }

 for (Integer x: numbers) {
  if (x <= n) {
   sum += reachNFloorSet(numbers, n - x, sum);
  }
 }
 return sum;
}

我认为问题出在for循环上,但是我无法弄清楚如何使其正确。

1 个答案:

答案 0 :(得分:2)

public class PlayMusic { /** * @param args the command line arguments */ public static void main(String args[]){ playMusic("Mars.wav"); } public static void playMusic(String filepath) { InputStream music; try{ music = new FileInputStream(new File(filepath)); AudioStream audios = new AudioStream(music); AudioPlayer.player.start(audios); } catch(IOException e){ JOptionPane.showMessageDialog(null,"Error"); } } 为负数或n中为0时,您将返回0或1,但应返回reachNFloorSet()sum。否则,您将丢弃所有累积的信息。

我认为最好重写您的方法,这样就不必担心已经采取了多少步骤:

sum + 1

您不必担心public static int reachNFloorSet (Set<Integer> numbers, int n) { if (n == 0) { return 1; } int sum = 0; for(Integer x: numbers) { if (x <= n) { sum += reachNFloorSet(numbers, n-x); } } return sum; } 是否为负数,因为您不必在可能发生的地方进行递归调用。 (当然,您还应避免在原始通话中使用否定n。)

相关问题