• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Combination Sum III

ind 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]]

Use recursion, or DFS

One syntax to notice is line 3:

List<List<Integer>> res = new ArrayList<List<Integer>>();

List is abstract and can not be instantiated

 1 public class Solution {
 2     public List<List<Integer>> combinationSum3(int k, int n) {
 3         List<List<Integer>> res = new ArrayList<List<Integer>>();
 4         List<Integer> item = new ArrayList<Integer>();
 5         helper(res, item, k, n, 1);
 6         return res;
 7     }
 8     
 9     public void helper(List<List<Integer>> res, List<Integer> item, int num, int remain, int start) {
10         if (remain < 0) return;
11         if (num == 0) {
12             if (remain == 0) {
13                 res.add(new ArrayList<Integer>(item));
14             }
15             return;
16         }
17         for (int i=start; i<=9; i++) {
18             item.add(i);
19             helper(res, item, num-1, remain-i, i+1);
20             item.remove(item.size()-1);
21         }
22     }
23 }

 

posted @ 2015-12-17 12:56  neverlandly  阅读(263)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3