中级农民
- 积分
- 195
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2012-7-6
- 最后登录
- 1970-1-1
|
我写了一下,但是输出结果很奇怪,比如说2.57的话,
输出结果是
Combination 0:
0.32, 0.95, 1.3,
但是prices里有0.65 and 1.3,按说结果还得有
0.32, 0.65, 0.65, 0.95才对啊,不知道问题在哪儿- public static void main(String[] args) {
- double[] prices = {0.32, 1.30, 3.37, 0.65, 0.95,2.30};
- List<List<Double>> result = combineSum(prices, 2.57);
- for(int i = 0; i < result.size();i++){
- System.out.println("Combination "+i+":");
- for(int j = 0; j < result.get(i).size();j++)
- System.out.print(result.get(i).get(j)+", ");
- System.out.println();
- }
- }
- private static List<List<Double>> combineSum(double[] prices, double target){
- List<List<Double>> result = new ArrayList<>();
- Arrays.sort(prices);
- dfs(prices, 0, target, new ArrayList<Double>(), result);
- return result;
- }
- private static void dfs(double[] prices, int index, double target, List<Double> sol, List<List<Double>> res){
- if(Double.compare(target, 0.0) == 0){
- res.add(new ArrayList<Double>(sol));
- return;
- }
- if(target < 0)
- return;
- for(int i = index; i < prices.length;i++){
- sol.add(prices[i]);
- dfs(prices, i, target-prices[i], sol, res);
- sol.remove(sol.size()-1);
- }
- }
复制代码 |
|