Why Runtime Error?


  • 0
    Y

    I have a Runtime error when n=1 and k=1. After adding the case 'if (k==1)' , I still have a Runtime error when n=4 and k=3. But my code runs well on these test cases. My IDE is Visiual Studio 2013 Express.
    Hope someone can help me figure out where the problem is. Here is my code. I have a WHILE loop to simulate k FOR loops.

    vector<vector<int> > combine(int n, int k) {
    	vector<vector<int> > result;
    	if (k > n) return result;
    	if (k == 0) return result;
    	if (k == 1)
    	{
    		for (int i = 1; i <= n; i++)
    		{
    			vector<int> tmp;
    			tmp.push_back(i);
    			result.push_back(tmp);
    		}
    		return result;
    	}
    	int* loop_index = new int[k];
    	memset(loop_index, 0, k*sizeof(int));
    	int ith = 0;
    	while (true)
    	{
    		if (ith >= k - 1)
    		{
    			vector<int> one_result;
    			for (int i = 0; i < k; i++)
    			{
    				one_result.push_back(loop_index[i] + 1);
    			}
    			result.push_back(one_result);
    			while (loop_index[ith] >= n + ith - k)ith--; 
    			if (ith < 0) break;
    			loop_index[ith]++;
    		}
    		else
    		{
    			loop_index[ith + 1] = loop_index[ith] + 1;
    			ith++;
    		}
    	}
    	delete[] loop_index;
    	return result;
    }

Log in to reply
 

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