Recursive Java Solution ,DP


  • 0
    N

    I think., the best advantage of recursive solution is easy to write.
    upload from my mobile phone,sorry for poor pattern
    public class Solution {

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

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

    public List<List<Integer>>  combine(int n, int k) {
        f(n, k);
        return c;
    }
    void f(int n, int k){
        if(k==data.size()){
            List<Integer> d= new ArrayList<Integer>();
          for(int s=0;s<data.size();s++) {
           d.add(data.get(s));
          }
        c.add(d);
        return;
        }
        int j=1;
        if(data.size()>0)
        j=data.get(data.size()-1)+1;//set the start point biger than last number
    
        for(;j<=n&&data.size()<=k;j++){
            data.add(j);
            f(n,k);
            data.remove(data.size()-1);
        }
        return;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.