216. Combination Sum III

    /*
     * 216. Combination Sum III 
     * 2016-6-12 by Mingyang
     * i一定要取到9,虽然大小聪明,想只取到7,但是后面的遍历可能也会遍历到9啊。
     * 1.长度标准:无(固定等于k)
     * 2.可选的范围:从start开始到9
     * 3.往前走一步:temp加入这个数,k-1表示又来了一位,n-i,然后i加1表示从下一位加起
     * 4.后退一步:temp减去这个数
     * 5.特别的case:剩下的小于0直接return
     * 6.关于重复:11 和1 在第一个1用了以后,第二个1就不用了
     * 错误点1:自己做的时候不知道i加到多少,题目已经明确说过到9就好了
     * 错误点2:就是下一轮dfs的start为i加1不是start加1
     */
    public static List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> temp = new ArrayList<Integer>();
        dfs(res, temp, k, n, 1);
        return res;
    }
    public static void dfs(List<List<Integer>> res, List<Integer> temp, int k, int n,int start) {
        if (k == 0) {
            if (n == 0) {
                res.add(new ArrayList<Integer>(temp));
            }
            return;
        }
        for (int i = start; i <= 9; i++) {
            temp.add(i);
            dfs(res, temp, k - 1, n - i, i+1);
            //这个地方非常容易错,就是下一个是i加1!!!!并不是start+1!!!!!!!!!!!!!!!!
            temp.remove(temp.size() - 1);
        }
    }
原文地址:https://www.cnblogs.com/zmyvszk/p/5579302.html