硬币找零细则问题

硬币找零:获得找零的各种情况,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();
        }

    }
}


全部评论

相关推荐

学不完不睡觉11:一眼点评,不过,看运气吧
点赞 评论 收藏
分享
点赞 评论 收藏
分享
神哥了不得:你简历字体有点不太协调呀,下面的字实在太小了呀,而且项目也不太行,建议换几个高质量的项目,面试会多很多
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务