硬币找零细则问题

硬币找零:获得找零的各种情况,candidates={3,6,7,9},target=9,输出[[3,3,3],[3,6],[9]]。动态规划只能得到不同情况的总数,不能获得具体结果。
import java.util.*;

public class Main {

    List<List<Integer>> results = new ArrayList<>();
    Set<String> unique = new HashSet<>();

    public static void main(String[] args) {
        int[] candidates = {3, 6, 7, 9};
        Main m = new Main();
        Arrays.sort(candidates);
        m.change(candidates, 9, new LinkedList<>());
        System.out.println(m.results.size());
    }

    public void change(int[] candidates, int target, LinkedList<Integer> result) {
        if(target == 0){
            StringBuilder key = new StringBuilder();
            List<Integer> temp = new LinkedList<>(result);
            Collections.sort(temp);
            for(int i : temp){
                key.append(i);
            }
            if(!unique.contains(key.toString())) {
                results.add(temp);
                unique.add(key.toString());
            }
            return;
        }

        for (int candidate : candidates) {
            result.offerLast(candidate);
            if (target - candidate >= 0) {
                change(candidates, target - candidate, result);
            }
            result.pollLast();
        }

    }
}


全部评论

相关推荐

风中翠竹:真的真的真的没有kpi。。。面试官是没有任何kpi的,捞是真的想试试看这个行不行,碰碰运气,或者是面试官比较闲现在,没事捞个人看看。kpi算HR那边,但是只有你入职了,kpi才作数,面试是没有的。
双非有机会进大厂吗
点赞 评论 收藏
分享
06-11 14:15
已编辑
门头沟学院 后端
田心今心:打招呼改一下,把实习半年以上随时到岗放第一行,因为ssob的hr不点击看的时候只能看前面几个字,你前面几个字hr获取不到什么信息,也就不会点进来看
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-24 12:26
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务