作者:跑车世界Y | 来源:互联网 | 2023-05-18 16:16
我试图计算总和为n的1,5,10和25的组合数.鉴于我不想重复(例如1 + 5 = 6和5 + 1 = 6).我正在使用hashSet
.我实现了一个名为的类ResultSet
,它在解决方案中保存了1,5,10和25的数量,并且我覆盖了该equals
方法.但是,由于某种原因,我的解决方案hashSet
不断返回重复值.为什么?
import java.util.HashSet;
public class Solution {
public static void main(String[] args) {
int N = 6;
int combinatiOnsSolution= new Combine(N).getSolution();
System.out.println("N= " + N + " Number of solutiOns= " + combinationsSolution);
}
}
class Combine {
private int solution;
private int n;
private HashSet cacheUnordered = new HashSet();
public Combine(int N) {
this.n = N;
this.solution = solve(n);
}
public int getSolution() {
return solution;
}
public int solve(int N) {
solve(N, 0, 0, 0, 0);
for (ResultSet r:cacheUnordered){
System.out.println(r.toString());
}
return cacheUnordered.size();
}
public void solve(int N, int substracted1, int substracted5, int substracted10, int substracted25) {
if (N == 0) {
cacheUnordered.add(new ResultSet(substracted1, substracted5, substracted10, substracted25));
} else if (N > 0) {
solve(N - 1, substracted1 + 1, substracted5, substracted10, substracted25);
solve(N - 5, substracted1, substracted5 + 1, substracted10, substracted25);
solve(N - 10, substracted1, substracted5, substracted10 + 1, substracted25);
solve(N - 25, substracted1, substracted5, substracted10, substracted25 + 1);
}
}
}
class ResultSet {
private int numberOf1;
private int numberOf5;
private int numberOf10;
private int numberOf25;
public ResultSet(int num1, int num5, int num10, int num25) {
numberOf1 = num1;
numberOf5 = num5;
numberOf10 = num10;
numberOf25 = num25;
}
@Override
public String toString(){
String result;
result = numberOf1 + " " + numberOf5 + " " + numberOf10 + " " + numberOf25;
return result;
}
@Override
public boolean equals(Object r2) {
if (r2 == null) {
return false;
}
if (!(r2 instanceof ResultSet)) {
return false;
}
ResultSet rr = (ResultSet) r2;
if (rr.numberOf1 == this.numberOf1 && rr.numberOf5 == this.numberOf5
&& rr.numberOf10 == this.numberOf10 && rr.numberOf25 == this.numberOf25) {
System.out.println("Comparing " + this.toString() + " to " + rr.toString());
return true;
} else {
return false;
}
}
public int getNum1() {
return numberOf1;
}
public int getNum5() {
return numberOf5;
}
public int getNum10() {
return numberOf10;
}
public int getNum25() {
return numberOf25;
}
}
dbank..
5
对于您的ResultSet
班级,您定义了一个equals()
方法,但没有定义hashCode()
方法.您需要两种方法HashSet
才能正常工作.请看这个解释.(它讨论HashMap,但它也适用于HashSet.)
1> dbank..:
对于您的ResultSet
班级,您定义了一个equals()
方法,但没有定义hashCode()
方法.您需要两种方法HashSet
才能正常工作.请看这个解释.(它讨论HashMap,但它也适用于HashSet.)