无限递归用于查找字符串的子集?

时间:2016-02-25 05:27:08

标签: java loops recursion infinite

我试图找到给定String的所有子集。例如,字符串"朗姆酒"会有子集“朗姆酒”,“茹”,“rm”,“r”,“嗯”,“你”,“m”和“”。 到目前为止,这是我的代码:

import java.util.Collections;
import java.util.ArrayList;
import java.util.List;
public class SubsetGenerator
{
    private String word;

    public SubsetGenerator(String in)
    {
        word=in;
    }
    public ArrayList<String> findSubsets()
    {
        ArrayList<String> subsets = new ArrayList<String>();
        String temp = word;
        if(temp.length()==1)
        {
            subsets.add(temp);
            return subsets;
        }
        else
        {
            String removed = temp.substring(0,1);
            temp = temp.substring(1);
            findSubsets();
            subsets.add(word);
        }
        return subsets;
    }

}

这是测试人员:

import java.util.Collections;
import java.util.ArrayList;
import java.util.List;
/**
 This program tests the subset generator.
*/
public class SubsetGeneratorTester
{
 public static void main(String[] args)
 {
 SubsetGenerator generator = new SubsetGenerator("rum");

 List<String> subsets = generator.findSubsets();
 // Sort the result for checking
 Collections.sort(subsets);
 System.out.println(subsets);
 System.out.println("Expected: [, m, r, rm, ru, rum, u, um]");
 }
}

2 个答案:

答案 0 :(得分:0)

你的方法有点令人困惑。我建议你使用类似的算法:

public class SubsetGenerator {  
    private String word;
    private ArrayList<String> list;

    public SubsetGenerator(String word) {
        //constructor and initialize variables
    }

    void findSubsets(String str) {
         list.add(str)

         for(int i = 0 ; i < str.length() ; i++) {
             String substring = /*str with char at index i removed*/
             this.findSubsets(substring);
         }
    }
}

这应包括所有变体。希望它有所帮助。

答案 1 :(得分:0)

我写了一个递归回溯解决方案:

import java.util.Collections;
import java.util.ArrayList;
import java.util.List;
public class SubsetGenerator
{
    private String word;
    private ArrayList<String> temp;

    public SubsetGenerator(String in)
    {
        word=in;
        temp = new ArrayList<String>();
    }
    public void solve(int idx, String s){
        if(idx == word.length()){
            temp.add(s);
            return;
        }
        solve(idx+1, s + word.charAt(idx));
        solve(idx+1, s);
    }
    public ArrayList<String> findSubsets(){
        solve(0, "");
        return temp;
    }
}