216. Combination Sum III

DFS+BackTracking,比较经典,逻辑上也很简单。。

public class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) 
    {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if(k == 0 || n == 0) return res;
        
        helper(res,k,n,new ArrayList<Integer>(),1);
        
        return res;
    }
    
    public void helper(List<List<Integer>> res, int k, int n, List<Integer> tempList,int t)
    {
        if(n < 0 || k < 0) return;
        else if(n == 0 && k == 0)
        {
            res.add(tempList);
        }
        else
        {
            if(k <= 0) return;
            else
            {
                for(int i = t; i <= 9;i++)
                {
                    if(n - i >= 0)
                    {
                        tempList.add(i);
                        helper(res,k-1,n-i,new ArrayList<Integer>(tempList),i+1);
                        tempList.remove(tempList.size()-1);
                    }
                    else break;
                }
            }
        }
    }
    
    
}

有一种说法是可以用暴力算法,因为只能1-9,可以直接算出总共多少种组合。。不明觉厉。



三刷。

做他妈的。。

time: O(n!)
space: O(k)

public class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<>();
        if (k == 0) return res;
        dfs(res, k, n, new ArrayList<>(), 1);
        return res;
    }
    
    public void dfs(List<List<Integer>> res, int k, int n, List<Integer> tempList, int m) {
        if (k == 0) {
            if (n == 0) {
                res.add(tempList);
            }
        } else {
            for (int i = m; i <= 9; i++) {
                if (n - i < 0) break;
                tempList.add(i);
                dfs(res, k - 1, n - i, new ArrayList<>(tempList), i + 1);
                tempList.remove(tempList.size() - 1);
            }
        }
    }
}
posted @ 2016-11-08 06:01  哇呀呀..生气啦~  阅读(81)  评论(0)    收藏  举报