Idiot-maker

  :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

https://leetcode.com/problems/combination-sum-iii/

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Ensure that numbers within the set are sorted in ascending order.


Example 1:

Input: k = 3, n = 7

Output:

 

[[1,2,4]]

 


Example 2:

Input: k = 3, n = 9

Output:

 

[[1,2,6], [1,3,5], [2,3,4]]

解题思路:

新题,与前面的系列相比,简单了一些,常规的dfs,没有啥好说的。

public class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> cur = new ArrayList<Integer>();
        dfs(k, n, res, cur, 1, 0);
        return res;
    }
    
    public void dfs(int k, int n, List<List<Integer>> res, List<Integer> cur, int step, int sum) {
        if(cur.size() == k && sum == n) {
            res.add(new ArrayList(cur));
            return;
        }
        if(cur.size() > k) {
            return;
        }
        if(cur.size() <= k && sum > n) {
            return;
        }
        for(int i = step; i < 10; i++) {
            cur.add(i);
            sum += i;
            dfs(k, n, res, cur, i + 1, sum);
            cur.remove(cur.size() - 1);
            sum -= i;
        }
    }
}

 //20181013

class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> cur = new ArrayList<Integer>();
        dfs(res, cur, k, n, 1, 0);
        return res;
    }
    
    public void dfs(List<List<Integer>> res, List<Integer> cur, int k, int n, int start, int sum) {
        if (cur.size() == k && sum == n) {
            res.add(new ArrayList(cur));
        }
        
        for (int i = start; i <= Math.min(n, 9); i++) {
            cur.add(i);
            dfs(res, cur, k, n, i + 1, sum + i);
            cur.remove(cur.size() - 1);
        }        
    }
}

 

posted on 2015-05-25 10:50  NickyYe  阅读(216)  评论(0编辑  收藏  举报