C++ c++;for循环异常
我正在写一个回溯算法,我认为我写的是正确的,但是输出是错误的。我去调试,发现执行:当程序在for循环中执行这个句子时,有时它会直接跳过for循环中的以下语句 问题是: 我已经编写了一个调试环境,可以直接运行 我的答案是:C++ c++;for循环异常,c++,backtrace,C++,Backtrace,我正在写一个回溯算法,我认为我写的是正确的,但是输出是错误的。我去调试,发现执行:当程序在for循环中执行这个句子时,有时它会直接跳过for循环中的以下语句 问题是: 我已经编写了一个调试环境,可以直接运行 我的答案是: class Solution { public: int index = 0, N, K; string ans; string getPermutation(int n, int k) { N = n; K = k; string
class Solution {
public:
int index = 0, N, K;
string ans;
string getPermutation(int n, int k) {
N = n;
K = k;
string str;
backtrace(str, 0);
return ans;
}
void backtrace(string &str, int start) {
if (start == N) {
index++;
if (index == K) {
ans = str;
}
return;
}
for (int i = start; i < N; i++) {
if (index == K) {
return;
}
string temp = str; //For loop to this sentence will not execute the following statement
str += to_string(i + 1);
backtrace(str, i + 1);
str = temp;
}
}
};
int nn(int n) {
if (n == 1) {
return 1;
}
return nn(n - 1) * n;
}
int main() {
Solution so;
for (int i = 1; i <= nn(3); i++) {
cout << so.getPermutation(3, i) << endl;
}
system("pause");
}
类解决方案{
公众:
int指数=0,N,K;
字符串ans;
字符串getPermutation(int n,int k){
N=N;
K=K;
字符串str;
回溯(str,0);
返回ans;
}
无效回溯(字符串和str,int start){
如果(开始==N){
索引++;
如果(索引==K){
ans=str;
}
返回;
}
for(int i=start;i 对于(int i=1;i我以前的想法是错误的,@Igor Tandetnik提醒我。这个问题需要一点数学技能,否则就会超时。谢谢你的帮助@john和@Igor Tandetnik。
我的最终代码如下:
class Solution {
private:
vector<int> hash;
vector<int> factorial;
bool flag = true;
void dfs(int cur, int n, int &k, string &ret, int &cnt, string path){
if(cur == n){
ret = path;
flag = false;
return;
}
int temp = factorial[n-cur-1];
for(int i=0; i<n; i++){
if(hash[i] && flag){
if(temp < k ){
k = k - temp;
continue;
}
path.push_back(i+1+'0');
hash[i] = 0;
dfs(cur+1,n,k,ret,cnt,path);
hash[i] = 1;
path.pop_back();
}
}
}
public:
string getPermutation(int n, int k) {
//calculate the factorial
if(n == 1) return "1";
factorial.resize(n);
factorial[0] = 1;
factorial[1] = 1;
if(n > 2){
for(int i=2; i<n; i++){
factorial[i] = i * factorial[i-1];
}
}
string ret;
string path;
hash.resize(n,1);
int cnt = 0;
dfs(0,n,k,ret,cnt,path);
return ret;
}
};
类解决方案{
私人:
向量散列;
向量阶乘;
布尔标志=真;
无效dfs(整数cur、整数n、整数和k、字符串和ret、整数和cnt、字符串路径){
如果(cur==n){
ret=路径;
flag=false;
返回;
}
int-temp=阶乘[n-cur-1];
对于(int i=0;i 2){
对于(int i=2;如果我怀疑这是你的问题。当我在调试器下运行你的代码时,没有跳过任何内容。可能你没有正确操作调试器。backtrace
生成的序列总是按顺序排列的。如果第一个数字是2
,那么第二个数字只能是3
,而不能是1
。此外,它还会生成ces短序列:当start==N
时,通常是str.size()
(这当然不是答案,但你可以这样声明)。