首页 > 其他 > 详细

Leetcode 216 组合总和III 初级01背包

时间:2020-07-03 14:43:48      阅读:62      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

  回溯解法:

    private List<List<Integer>> anList = new LinkedList<List<Integer>>();

    public final List<List<Integer>> combinationSum3(int k, int n) {
        combinationSum3DP(k, n, new Stack<Integer>(),1);
        return anList;
    }

    /**
     * @Author Niuxy
     * @Date 2020/7/3 12:51 下午
     * @Description k 个和为 n 的子序列,需要找到所有序列,不能简单地定义状态转移方程。
     * 必须遍历整个解空间。
     * 每个元素从小到大随机选取,天然有序,不需要额外的去重工作
     * 背包问题变种,将视角从整体放到局部,每个元素都有两种状态,选择或不选择。
     */
    public final void combinationSum3DP(int k, int n, Stack<Integer> anStack,int flag) {
        if (n <= 0 && k != 0) {
            return;
        }
        if (k == 0) {
            if (n != 0) {
                return;
            }
            anList.add(new ArrayList<Integer>(anStack));
            return;
        }
        for (int i = flag; i < 10; i++) {
            if (anStack.contains(i)) {
                continue;
            }
            anStack.push(i);
            combinationSum3DP(k - 1, n - i, anStack,+1);i
            //回溯
            anStack.pop();
        }
    }

技术分享图片

 

Leetcode 216 组合总和III 初级01背包

原文:https://www.cnblogs.com/niuyourou/p/13229852.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!