zoukankan      html  css  js  c++  java
  • 组合数

    问题: 给n个不同的正整数, 取m个数使得和为sum, 其中任意数可以重复取多次

    例如:set [2, 3, 6, 7] and target 7, 结果有[7] ,[2,2,3] 

    public class Solution {
        public List<List<Integer>> combinationSum(int[] candidate, int sum){       
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            //corner

            //core
            List<Integer> path = new ArrayList<>();

            Arrays.sort(candidate);

            helper(res, path, candidate, sum, 0);        //start from position = 0

            return res;
        }

        public void helper(List<List<Integer>> res, List<Integer> path, int[] candidate, int sum, int position){
            //base
            if ( sum == 0 ){                                   
                res.add(new ArrayList<Integer>(path));
                return ;                                       
            }

            //current
            for ( int i = position; i < candidate.length && sum >= candidate[i]; i++ ){   
                path.add(candidate[i]);
                //next: pass down remaining 'sum', and afterwards 'start position'
                helper(res, path, candidate, sum - candidate[i], i);       
                path.remove(path.size() - 1);
            }

            return ;
        }
    }

  • 相关阅读:
    test
    ws318 配置
    电影地址:
    白岩松给青少年的7个忠告,值得好好阅读~
    干部带队伍的四个知道,一个跟上
    CDOJ 1259 昊昊爱运动 II bitset+线段树
    codeforces 508D . Tanya and Password 欧拉通路
    poj 1041 John's trip 欧拉回路
    poj 1651 Multiplication Puzzle 区间dp
    poj 2955 Brackets 区间dp
  • 原文地址:https://www.cnblogs.com/energy1010/p/6867391.html
Copyright © 2011-2022 走看看