A golang solution


  • 0
    N
    func backTrack(start int, end int, k int, s []int) [][]int{
    	r := [][]int{}
    
    	for i := start; i <= end && && end - start + 1 >= k; i++ {
    		if k == 1 {
    			t := append([]int(nil), s...)
    			t = append(t, i)
    			r = append(r, t)
    		} else {
    			s = append(s, i)
    			for _, v := range backTrack(i + 1, end, k - 1, s) {
    				r = append(r, v)
    			}
    			s = s[:len(s) - 1]
    		}
    	}
    	return r
    }
    
    func combine(n int, k int) [][]int {
    	if k <= 0 {
    		return [][]int{{}}
    	} else if k >=n {
    		s := []int{}
    		for i := 1; i <= n; i++ {
    			s = append(s, i)
    		}
    		return [][]int{s}
    	} else if k == 1 {
    		r := [][]int{}
    		for i := 1; i <= n; i++ {
    			r = append(r, []int{i})
    		}
    		return r
    	}
    
    
    	return backTrack(1, n, k, []int{})
    }

Log in to reply
 

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