2015年11月3日星期二

Leetcode 216 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]]
Solution 1: Use back tracking method. Terminate condition is (1) reach depth of k, generate possible result. (2) num>9 not valid, (3) num>n, not valid as in ascending  order.
 public class Solution {  
   public List<List<Integer>> combinationSum3(int k, int n) {  
     List<List<Integer>> res=new ArrayList<>();  
     if (k>9 || k<0) return res;  
     if (n<1 || n>45) return res;  
     List<Integer> one=new ArrayList<>();  
     dfs(0,1,k,n,one,res);  
     return res;  
   }  
   private void dfs(int d, int num, int k, int n, List<Integer> one, List<List<Integer>> res) {  
     if (d==k) {  
       if (n==0) res.add(new ArrayList<Integer>(one));  
     }  
     else if (num<=9 && num<=n) {  
       dfs(d,num+1,k,n,one,res);  
       one.add(num);  
       dfs(d+1,num+1,k,n-num,one,res);  
       one.remove(one.size()-1);  
     }  
   }  
 }  

没有评论:

发表评论