简体   繁体   English

通过回溯查找求和 n 的所有子集

[英]Finding all the subsets that sum n via backtracking

I want to find all the integer subsets that sum n via backtracking我想找到所有通过回溯求和 n 的 integer 子集

For example for the integers:例如对于整数:

1 2 3 4 5 6 7

and n = 7 n = 7

I want to ouput我想输出

1 2 4
1 6
2 5
3 4
7 

I think that I should pass the position in the integer array that I'm evaluating as argument, but I'm stuck writing the rest of the logic.我认为我应该在我正在评估的 integer 数组中传递 position 作为参数,但我一直坚持编写逻辑的 rest。

My code so far:到目前为止我的代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

/**
 *
 * @author talleres
 */
public class Main {




int sum (TreeSet<Integer>ts, int temp) {

    int sum=0;

    for (Integer i: ts){

        sum +=i;

    }

    return sum+temp;
}



static HashSet<TreeSet<Integer>> alternatives = new HashSet <TreeSet<Integer>>();
static ArrayList<TreeSet<Integer>> subsets = new ArrayList <TreeSet<Integer>>();

static TreeSet<Integer> getNextSubset (){

    TreeSet<Integer> alternative = new TreeSet<Integer>();

    if (!alternatives.contains(alternative)){   
        return alternative;   
    }
    else return null; // BEWARE!! 
} 

static void findSubsets (ArrayList<Integer> numbers, int amount, int index){


    TreeSet <Integer> subset = new TreeSet<Integer>();

    int temp = numbers.get(index); //initialize alternative

    if (temp<=amount)
        subset.add(temp);

    if (temp==amount)
        subsets.add(subset);




}


    public static void main(String[] args) throws IOException {
        // TODO code application logic here

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("inset integers");

        ArrayList<Integer> numeros = new ArrayList<Integer>();
        String line=br.readLine();

        while (!line.equals("")){
            numeros.add (Integer.parseInt(line));
            line = br.readLine();
        }

        Collections.sort(numeros);

        System.out.println("insert the amount the subsets should sum");
           line = br.readLine();

        int amount = Integer.parseInt(line);

        ArrayList<Integer> accum = new ArrayList<Integer>();

        findSubsets(numeros, amount, 0);


    }

}

Here's some pseudo code for you to work with:这里有一些伪代码供您使用:

Set<Set<Integer>> subsets(Set<Integer> remaining, int n) {
    results = new HashSet<Set<Integer>>();

    if (n == 0)
        results.add(empty set);

    for each i in remaining
        newRemaining = remaining \ {i}

        for each subresult in subsets(newRemaining, n - i)
            results.add(subresult + {i})

    return results
}

Should work for negative numbers as well.也应该适用于负数。 (uhm, actually will work. I implemented it and tested it before writing the pseudo code:-) (嗯,实际上工作。我在编写伪代码之前实现并测试了它:-)

I might be tempted to do this in a recursive function.我可能很想在递归 function 中执行此操作。 It feels straightforward.感觉很直接。 It might not be the best, but it will work well.它可能不是最好的,但它会运作良好。

This is very much in pseudo-code and assumes the numbers are 1..END.这在伪代码中非常多,并假设数字是 1..END。 If you are given a list, sorting and then using list[i] would be appropriate.如果给你一个列表,排序然后使用 list[i] 将是合适的。

find(int curpos,int cursum,int sumleft,char output[])
{
  if (sumleft == 0)
   print(output);
  if (curpos > sumleft)
   return;
  for(i=curpos;i<=TARGET && i<=sumleft)
    find(i+1,cursum+i,sumleft-i,output+i."+%d")
}

main()
{
  char output[100];
  find(1,0,TARGET,"");
}

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

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