您的位置:首页 > 编程语言 > C语言/C++

Combination Sum III

2016-04-29 15:35 288 查看
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]]


解答:

1.我的方法,回溯

//
//  main.cpp
//  Combination Sum III
//
//  Created by zjl on 16/4/29.
//  Copyright © 2016年 zjl. All rights reserved.
//

#include <iostream>
#include <vector>
using namespace std;

void combination(vector<vector<int>>& res,vector<int> list,vector<int>& vec,int begin,int k,int n){
if(k==0 && n==0){
res.push_back(vec);
return;
}
for(int i = begin; i < list.size(); i++){
if(n >= list[i]){
vec.push_back(list[i]);
combination(res,list,vec,i+1,k-1,n-list[i]);
vec.pop_back();
}else return;
}
}

vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int>> res;
vector<int> vec;
vector<int> list;
int begin = 0;
if(k >= n)
return res;
for(int i = 0; i < n; i++)
list.push_back(i+1);
combination(res,list,vec,begin,k,n);
return res;
}
void print_vec(vector<vector<int>> v){
for(int i = 0; i < v.size(); i++){
for(int j = 0; j < v[i].size(); j++){
cout<<v[i][j]<<" ";
}
cout<<endl;
}
}

int main(int argc, const char * argv[]) {
int k = 3;
int n = 9;
vector<vector<int>>res = combinationSum3(k, n);
print_vec(res);
return 0;
}


输出:

1 2 6 
1 3 5 
2 3 4

注:这里

combination(res,list,vec,i+1,k-1,n-list[i]);



combination(res,list,vec,begin+1,k-1,n-list[i]);

输出的答案是不一样的。
以 i+1 输出的是从i以后的遍历得到的结果,就如以上答案所示。若以begin+1传递,则是下次遍历也从begin开始。得到的答案为以下:

1 2 6 
1 3 5 
1 4 4 
1 5 3 
2 2 5 
2 3 4 
2 4 3 
3 2 4 
3 3 3 
4 2 3 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ leetcode backtracking