Java 到达n’;第四级楼梯,但具有给定的圆锥形
有Java 到达n’;第四级楼梯,但具有给定的圆锥形,java,algorithm,Java,Algorithm,有n楼梯,站在底部的人想爬到顶部。该人员一次可以爬1级或2级楼梯 现在我想找到所需的最小步数,它可以被给定的m整除 下面是我使用创建的java程序,用于打印可能的步骤: public static void main(String args[]) { int n = 10, m = 2; List<Integer> vals = new ArrayList<>(); Set<String> set = new T
n
楼梯,站在底部的人想爬到顶部。该人员一次可以爬1级或2级楼梯
现在我想找到所需的最小步数,它可以被给定的m整除
下面是我使用创建的java程序,用于打印可能的步骤:
public static void main(String args[]) {
int n = 10, m = 2;
List<Integer> vals = new ArrayList<>();
Set<String> set = new TreeSet<>(Comparator.reverseOrder());
ClimbWays(n, 0, new int[n], vals, set);
set.forEach(a -> {
System.out.println(a + " : " + a.length());
});
}
public static void ClimbWays(int n, int currentIndex, int[] currectClimb, List<Integer> vals, Set<String> set) {
if (n < 0)
return;
if (n == 0) {
vals.add(currentIndex);
int last = 0;
StringBuilder sb = new StringBuilder();
for (int i = currentIndex - 1; i >= 0; i--) {
int current = currectClimb[i];
int res = current - last;
last = current;
sb.append(res);
}
String s = sb.toString();
char[] c = s.toCharArray();
Arrays.sort(c);
s = new String(c);
set.add(s);
return;
}
currectClimb[currentIndex] = n;
ClimbWays(n - 1, currentIndex + 1, currectClimb, vals, set);
ClimbWays(n - 2, currentIndex + 1, currectClimb, vals, set);
}
现在对于步骤10,如果我想得到可被m=2整除的最小步数,那么解决方案是112222
,其中需要的步数是6
这个程序基本上会找到所有可能的对,然后将它们添加到树集中。接下来,我可以循环遍历这个集合,得到可以被给定输入m
整除的最小元素
有更好的方法吗?因为一个人一次最多可以爬两步,所以爬n级楼梯的最小步数是
x = n/2 if n is even
x = n/2 + 1 if n is odd
现在你需要找到爬n级楼梯的最小步数,它可以被m整除。这意味着你需要找到一个紧挨着x的数字,它可以被m整除
if x%m == 0 then x is your answer
if x%m != 0 then ((x/m) + 1) * m is your answer.
现在谈谈你的例子
For n = 10,
x = n/2 = 5,
x%m = 5 % 2 = 1 != 0
Thus ans = ((5/2) + 1) * 2 = 6
由于该人员一次最多可爬2步,因此爬n级楼梯的最小步数为
x = n/2 if n is even
x = n/2 + 1 if n is odd
现在你需要找到爬n级楼梯的最小步数,它可以被m整除。这意味着你需要找到一个紧挨着x的数字,它可以被m整除
if x%m == 0 then x is your answer
if x%m != 0 then ((x/m) + 1) * m is your answer.
现在谈谈你的例子
For n = 10,
x = n/2 = 5,
x%m = 5 % 2 = 1 != 0
Thus ans = ((5/2) + 1) * 2 = 6
我不明白你的问题。你能详细解释一下吗?@Bugman,我更新了问题以澄清,你也可以参考我在问题中添加的链接。我不理解你的问题。你能详细解释一下吗?@Bugman,我更新了问题以澄清,你也可以参考我在问题中添加的链接。