题目链接: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.
Note:
- All numbers will be positive integers.
- The solution set must not contain duplicate combinations.
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]]
思路:
比较简单,回溯即可。
AC
Runtime: 0 ms, faster than 100.00% of Java online submissions for Combination Sum III.
Memory Usage: 33.7 MB, less than 5.02% of Java online submissions for Combination Sum III.
class Solution {
List<List<Integer>> ans=new ArrayList();
public List<List<Integer>> combinationSum3(int k, int n) {
if(k<1||n<1)
return ans;
helper(0,0,k,n,new ArrayList<Integer>(),0);
return ans;
}
public void helper(int i,int sum,int k,int n,List<Integer> list,int count){
if(sum>n||count>k)
return;
if(count==k&&sum==n){
ans.add(new ArrayList(list));
}
for(i=i+1;i<=9;i++){
list.add(i);
sum+=i;
count++;
helper(i,sum,k,n,list,count);
count--;
sum-=i;
list.remove(list.size()-1);
}
}
}