zoukankan      html  css  js  c++  java
  • 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.


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

    Credits:
    Special thanks to @mithmatt for adding this problem and creating all test cases.

    解题思路:

    深搜?因为在9之内所以时间应该不会很高。

    1. class Solution {  
    2.     private:  
    3.               
    4.      vector<vector<int>> ret;  
    5.     vector<int> store;  
    6.   
    7.     void deep(int &k,int &n,int cur_num,int count,int sum){  
    8.         count++;  
    9.         sum+=cur_num;  
    10.         store.push_back(cur_num);  
    11.         if(count == k){  
    12.             if(n==sum) {ret.push_back(store);return;}  
    13.         }  
    14.         else{  
    15.             for(int j=cur_num+1;j<=9;j++){  
    16.                 deep(k,n,j,count,sum);  
    17.                 store.pop_back();  
    18.             }  
    19.         }  
    20.     }  
    21. public:  
    22.     vector<vector<int>> combinationSum3(int k, int n) {  
    23.           
    24.   
    25.         for(int i=1;i<=9;i++){  
    26.             if((9-i+1)>=k)  
    27.             deep(k,n,i,0,0);  
    28.             store.clear();  
    29.   
    30.         }  
    31.         return ret;  
    32.     }  
    33. };  
  • 相关阅读:
    CopyOnWriteArrayList
    Herriot
    Prefix tree
    hadoop 测试框架
    Hadoop RPC
    OpenCV2马拉松第2圈——读写图片
    LCD深度剖析
    SharePoint 改动passwordWeb Part部署方案
    android小游戏模版—重力感应
    CSS(层叠样式表)基础知识
  • 原文地址:https://www.cnblogs.com/liangyc/p/8820082.html
Copyright © 2011-2022 走看看