回溯求数组的子集JAVA,通过回溯找到所有合计n的子集

I want to find all the integer subsets that sum n via backtracking

For example for the integers:

1 2 3 4 5 6 7

and 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.

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 (TreeSetts, int temp) {

int sum=0;

for (Integer i: ts){

sum +=i;

}

return sum+temp;

}

static HashSet> alternatives = new HashSet >();

static ArrayList> subsets = new ArrayList >();

static TreeSet getNextSubset (){

TreeSet alternative = new TreeSet();

if (!alternatives.contains(alternative)){

return alternative;

}

else return null; // BEWARE!!

}

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

TreeSet subset = new TreeSet();

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 numeros = new ArrayList();

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 accum = new ArrayList();

findSubsets(numeros, amount, 0);

}

}

解决方案

Here's some pseudo code for you to work with:

Set> subsets(Set remaining, int n) {

results = new HashSet>();

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 :-)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值