码迷,mamicode.com
首页 > 其他好文 > 详细

自己搞清楚的第一个树结构,用树生成全排列

时间:2020-05-09 23:27:41      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:ted   array   pop   div   排列   stat   toc   lin   null   

import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.Stack;

public class Main07 {
    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()) {
            String str = sc.nextLine();
            str = str.trim();
            String[] strs = str.split("\\s");
            
            //划分
            int count = Integer.parseInt(strs[0]);
            String[] dict = Arrays.copyOfRange(strs, 1, count+1);
            //System.out.println(Arrays.asList(dict).toString());
            
            //看兄弟单词,组合所有兄弟单词;
            String bro = strs[count + 1];
            char[] charArray = bro.toCharArray();
            LinkedList<String> linkedList = new LinkedList<String>();
            perm(charArray,new Stack<>(),linkedList);
            linkedList = new LinkedList<String>(new HashSet<>(linkedList));
            linkedList.remove(bro);
            
            //查找
            int co = 0;
            for (int i = 0; i < linkedList.size(); i++) {
                for (int j = 0; j < dict.length; j++) {
                    if(linkedList.get(i).equals(dict[j])) {
                        co++;
                    }
                }
            }
            System.out.println(co);
            
            
            //输出指定目录
            String orderstr = strs[count + 2];
            System.out.println(dict[Integer.parseInt(orderstr)]);
            
            dict = null;
            
        }
        
    }

    private static void perm(char[] charArray, Stack stack, LinkedList<String> linkedList) {
        // TODO Auto-generated method stub
        if(charArray.length==0) {
            String a = "";
            for (int i = 0; i < stack.size(); i++) {
                a=a+stack.get(i);
            }
            linkedList.add(a);
        }
        
        for (int i = 0; i < charArray.length; i++) {
            char[] Array = new char[charArray.length-1];
            System.arraycopy(charArray, 0, Array, 0, i);
            System.arraycopy(charArray, i+1, Array, i, charArray.length-i-1);
            stack.push(charArray[i]);
            perm(Array,stack,linkedList);
            stack.pop();
        }
    }
}

 

自己搞清楚的第一个树结构,用树生成全排列

标签:ted   array   pop   div   排列   stat   toc   lin   null   

原文地址:https://www.cnblogs.com/RYSBlog/p/12860544.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!