简体   繁体   English

组合需要第5个字符串

[英]5th string needed from combination

Suppose there is a string s=abcd 假设有一个string s=abcd

I want the 5th string consisting of a , b , c , d , which is adbc . 我想要第5个字符串,包括abcd ,这是adbc But I also get all the answers beyond it which I don't need. 但我也得到了我不需要的所有答案。

So how can I stop this method after its 5th execution? 那么如何在第5次执行后停止此方法呢?

import java.util.Arrays;
import java.util.Scanner;

class Test{
   long times;
   int n=1;

   public static void main(String[] args) {
        Test tm=new Test();
        Scanner in=new Scanner(System.in);
        int t=Integer.parseInt(in.nextLine());

        while(t!=0){
            String s=in.nextLine();
            char ch[]=s.toCharArray();          
            Arrays.sort(ch);
            String sort=String.valueOf(ch);            
            String ans;
            long n=Long.parseLong(in.nextLine());
            tm.times=n;
            tm.permu("",sort);
            t--;           
        }
    }

    private void permu(String prefix,String str) {
        int len=str.length();          

        if(len==0){
            if(n==times){
                System.out.println(prefix);
            }
            else{
                n++;
            }
        }
        else{
            for(int i=0;i<len;i++){
                permu(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, len));
            }
        }      
    }
}

Secondly is there any site where I can read about permutation, combination and probability for calculating and finding the permutation, combination and probability... For coding thing not for mathematical thing..ie I know how to solve mathematically but I can't code it.. Unable to write logic for it. 其次是有任何网站,我可以阅读有关排列,组合和概率的计算和发现排列,组合和概率......对于编码的东西不是为了数学的东西..我知道如何数学解决但我不能编码它..无法为它编写逻辑。

You don't change n after running the check and printing a result in your recursion. 运行检查并在递归中打印结果后,不要更改n That's why you print everything after adbc . 这就是你在adbc之后打印所有内容的原因。

If you use this code when checking: 如果您在检查时使用此代码:

if (n == times) {
    System.out.println(prefix);
    n = -1;
} else {
    if (n > -1)
        n++;
}

then you only get n == times to be true once, and that's when the prefix is adbc . 那么你只需要n == times为真,那就是prefixadbc

Example test for the solution: 解决方案的示例测试:

产量

If you want to stop a method that has no return value (has void in its return type in the method signature), then calling return; 如果要停止一个没有返回值的方法(方法签名中的返回类型为void ),则调用return; will exit the method... But it isn't needed here. 将退出该方法......但这里不需要它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM