How Monkeys climb steps

Source: Internet
Author: User

Monkey steps:

A monkey is very naughty and likes to climb steps. But because the monkey is too small, it can only climb one or two steps in one step. Calculate all possible crawling paths of the monkey.


package shuai.study.steps;import java.util.ArrayList;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Set;/** * @author shengshu *  */public class MonkeyCrawl {// Get paths, which will be permutatedpublic static Set<String> getPathsSet(int steps) {Set<String> pathsSet = new HashSet<String>();for (int i = 0; i <= steps / 2; i++) {int twoStepSum = i * 2;int oneStepTimes = steps - twoStepSum;StringBuffer pathStringBuffer = new StringBuffer();for (int x = 0; x < oneStepTimes; x++) {// "-" represent one steppathStringBuffer.append("-");}for (int y = 0; y < i; y++) {// "=" represent two stepspathStringBuffer.append("=");}pathsSet.add(pathStringBuffer.toString());}return pathsSet;}// Permutate all possible pathspublic static void permutatePaths(String path, List<String> list) {if (path.length() == 1) {for (int i = 0; i < list.size(); i++) {System.out.print(list.get(i));}System.out.println(path);} else {int index[] = new int[path.length()];for (int i = 0; i < index.length; i++) {index[i] = path.indexOf(path.charAt(i));}for (int i = 0; i < path.length(); i++) {String subPath = path.substring(1, path.length());if (i == index[i]) {list.add("" + path.charAt(0));permutatePaths(subPath, list);list.remove(list.size() - 1);}path = subPath + path.charAt(0);}}}public static void main(String[] args) {// Set steps as 15, or othersSet<String> pathsSet = MonkeyCrawl.getPathsSet(15);Iterator<String> iterator = pathsSet.iterator();while (iterator.hasNext()) {String path = iterator.next();MonkeyCrawl.permutatePaths(path, new ArrayList<String>());}}}


How Monkeys climb steps

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.